开发者

asp.net mvc 3 rc1. ModelBinder populates all properties with null

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.ParentPrope开发者_JS百科rty", 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.


Use the HiddenFor(...) helper instead.


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.

public class ParentEntityInfo
{
    [Required(ErrorMessage = "Parent required")]
    public long? ParentId { get; set; }
    public string EntityName { get; set; }
    public string ParentProperty { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜