问题
I have a class:
public class ClientInformation{
public string UserName {get; set;}
public ICollection<RegionDistrictCity> RegionDistrictCity
{
get;
set;
}
public class RegionDistrictCity
{
public string Region { get; set; }
public string District { get; set; }
public string City { get; set; }
}
}
How should be formated the name attribute of input elements for properties Region, Distirct, City in html in order to make model binder populate collection "ICollection RegionDistrictCity"?
I tried to have an action method with parameter of type "ClientInformation" and html name attributes formated like "[index].PropertyName" but in that case only the property "UserName" is binded.
I tried to have action method with parameter name "client" and have html names attributes formated like "client[index].PropertyName" but it doesn't work. (in tha case if I there is a "List client" then it would get populated)
Thanks.
回答1:
In MVC4 you should use a for loop instead of a foreach to bind your collection. Then the model binder will be able to populate your model when you submit your data.
@for (int i = 0; i < Model.RegionDistrictCity.Count; i++)
{
@Html.EditorFor(model => Model.RegionDistrictCity[i].Region)
}
But this will only work if you are not deleting or adding items to your collection dynamically. If you want to do that, you should use the BeginCollectionItem helper created by steve sanderson. http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
来源:https://stackoverflow.com/questions/18412765/asp-net-mvc-model-binding-to-nested-collection