asp.net - MVC模型绑定到嵌套集合 [英] asp.net - MVC model binding to nested collection
问题描述
我有一个类:
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; }
}
}
应该如何格式化的HTML输入元素的属性地区,Distirct,市的name属性,以使模型绑定填充集的ICollection RegionDistrictCity?
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"?
我想有一个动作的方法,类型为ClientInformation的参数和HTML属性名称格式化,如[指数] .PropertyName但在这种情况下,只有财产用户名的绑定。
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.
我想有行动方法,参数名客户,并有HTML属性的名称格式化,如客户端[指数] .PropertyName,但它不工作。 (塔中的情况下,如果我有一个客户名单,那么它会得到填充)
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)
感谢。
推荐答案
在MVC4您应该使用 的for循环,而不是一个foreach 的绑定您的收藏。然后模型绑定就能当您提交的数据填充模型。
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)
}
但这个如果你不删除或动态地添加项目到您的收藏只会工作。
如果你想这样做,你应该使用由史蒂夫·桑德森创建的BeginCollectionItem帮手。的http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
这篇关于asp.net - MVC模型绑定到嵌套集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!