MVC model naming convention for child objects?

I am having problems with the default default binding naming assignment when there is a child property. For instance:

I have a ViewModel that looks something like this:

public class UserViewModel { public User BusinessObject { get; set; } } 

The My User class has the NetworkLogin property.

My View has something like this: <%: Html.LabelFor (model => model.BusinessObject.NetworkLogin)%> <%: Html.TextBoxFor (model => model.BusinessObject.NetworkLogin)%> Autocomplete

And my controller, what I would like to do,

  [HttpGet] public ActionResult UserIndex(string networkLogin) { } 

Problem: The input parameter "networkLogin" is always zero. This makes sense because the actual parameter in the html element is name = "BusinessObject.NetworkLogin" and id = "BusinessObject_NetworkLogin". However, I do not know which parameter name I should use in my action method. I tried "businessObject_NetworkLogin" and it does not work either.

However, I have this workaround that really works, but I don't like it. I add this to my ViewModel:

  public string NetworkLogin { get { if (BusinessObject == null) BusinessObject = new User(); return BusinessObject.NetworkLogin; } set { if (BusinessObject == null) BusinessObject = new User(); BusinessObject.NetworkLogin = value; } } 

And now my browse page is talking about this. <%: Html.TextBoxFor (model => model.NetworkLogin)%>

Can someone tell me what the proper naming convention is for binding the model by default, so that I don't need to use the above workaround?

Thanks!

+4
source share
1 answer

Specify the prefix so that the middleware networkLogin that the BusinessObject.NetworkLogin query string parameter actually refers to networkLogin , which is what you use as the action argument

 public ActionResult UserIndex( [Bind(Prefix = "BusinessObject")] string networkLogin ) { ... } 

or reusing your view model:

 public ActionResult UserIndex(UserViewModel model) { // TODO: use model.BusinessObject.NetworkLogin // which is gonna be correctly bound here ... } 

As for your workaround, after you include one of my two suggestions, your view model property should look like this:

 public string NetworkLogin { get; set; } 
+11
source

All Articles