ASP.NET MVC 3 RC1。 ModelBinder 用 null 填充所有属性
我有一个像这样的对象
public class ParentEntityInfo
{
public long? ParentId { get; set; }
public string EntityName { get; set; }
public string ParentProperty { get; set; }
}
,该对象的视图是:
<%=Html.Hidden("parentInfo.ParentId", parentInfo.ParentId)%>
<%=Html.Hidden("parentInfo.ParentProperty", parentInfo.ParentProperty)%>
<%=Html.Hidden("parentInfo.EntityName", parentInfo.EntityName)%>
我遇到了parentInfo 为空的情况,我将此表单发布到控制器。在控制器操作上,
public ActionResult SomeAction(..., ParentEntityInfo parentInfo)
我收到构造的对象parentInfo,但所有属性均为空。在这种情况下,我宁愿让整个parentInfo 为空。我有没有可能告诉默认模型绑定器不传递这样的对象?或者我可以修改这段代码中的某些内容以使其以这种方式工作。我认为在 mvc 2.0 中它是这样工作的。
I have an object like this
public class ParentEntityInfo
{
public long? ParentId { get; set; }
public string EntityName { get; set; }
public string ParentProperty { get; set; }
}
and view for this object is:
<%=Html.Hidden("parentInfo.ParentId", parentInfo.ParentId)%>
<%=Html.Hidden("parentInfo.ParentProperty", parentInfo.ParentProperty)%>
<%=Html.Hidden("parentInfo.EntityName", parentInfo.EntityName)%>
I have the case where parentInfo is null and I post this form to controller. On the controller action
public ActionResult SomeAction(..., ParentEntityInfo parentInfo)
I receive constructed object parentInfo but all properties are null. In this case I would rather prefer to have whole parentInfo to be null. I there any possibility to tell default model binder do not pass such object? Or probably I can modify something in this code to make it work this way. I think in mvc 2.0 it worked this way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请改用
HiddenFor(...)
帮助器。Use the
HiddenFor(...)
helper instead.我认为默认的模型绑定器将始终使用 Activator.CreateInstance 来绑定复杂的操作参数。您可以做的是使用 ModelState.IsValid 来评估参数是否绑定成功。我认为在你的情况下,默认情况下这将是错误的,但如果不是,你可以添加必要的属性来确保这种行为,例如
I think the default model binder will always use Activator.CreateInstance to bind complex action parameters. What you can do is use ModelState.IsValid to assess whether the parameter was bound successfully. I think in your case this will be false by default, but if not you could add the necessary attribute to ensure this behaviour e.g.