默认模型绑定器未映射模型中的集合。这是我的代码:
型号:
public class Company
{
public string Name;
public List<CompanyActivity> Activities
}
public class CompanyActivity
{
public string Code;
public string Description
}
控制器:
[HttpPost]
public ActionResult Index(Company company) {}
查看/ HTML:
<input name="Name" type="text" value="some name" />
<input name="Activities[0].Code" type="text" value="1" />
<input name="Activities[0].Description" type="text" value="a" />
<input name="Activities[1].Code" type="text" value="2" />
<input name="Activities[1].Description" type="text" value="b" />
已映射名称输入,但“活动”列表为空。
答案 0 :(得分:1)
您已使用字段定义了模型,但必须使用属性。您只需为此更改模型:
public class Company
{
public string Name { get; set; }
public List<CompanyActivity> Activities { get; set; }
}
public class CompanyActivity
{
public string Code { get; set; }
public string Description { get; set; }
}
字段和属性之间的差异:Difference between Property and Field in C# 3.0+和ASP.net MVC - Model binding excludes class fields?
答案 1 :(得分:0)
名称必须相同才能将它们构建为集合/数组:
我会创建一个ViewModel来处理这种情况,这就是为什么我几乎总是构建一个ViewModel来处理视图渲染和MVC的特性。
<强>模型强>
public class Company
{
public string Name;
public List<CompanyActivity> Activities
}
<强>视图模型强>
public class CompanyViewModel
{
public string Name;
//View specific
public List<int> CompanyActivityCodes
}
查看强>
<input name="Name" type="text" value="" />
<input name="CompanyActivityCodes" type="text" value="" />
<input name="CompanyActivityCodes" type="text" value="" />
然后绑定CompanyActivityCodes属性,然后可以重新分配这些属性以在控制器中构建Activities属性。
public ActionResult Index(CompanyViewModel companyViewModel)
{
var company = new Company { Name = companyViewModel };
company.Activities = companyViewModel.CompanyActivityCodes.Select(x => new CompanyActivity { Code = x });
}
答案 2 :(得分:0)
应该是
<input name="company.Activities[0].Code" type="text" value="" />