我有一个模型ApplicantBranchList
,该模型在较大的模型中用作属性,如下所示:
[Display(Name = "Where would you want to work?")]
public ApplicantBranchList PreferedBranches { get; set; }
ApplicantBranchList
:public class ApplicantBranchList : ViewModel
{
public ApplicantBranchItem HeaderItem { get; set; }
public ApplicantBranchList()
{
HeaderItem = new ApplicantBranchItem();
}
public void MapFromEntityList(IEnumerable<ApplicantBranch> applicantBranches)
{
var service = new BranchService(DbContext);
var selectedIds = applicantBranches.Select(b => b.BranchId);
Items = service.ReadBranches()
.Where(i => !i.IsDeleted)
.Select(p => new ApplicantBranchItem { BranchName = p.Name, WillWorkAt = selectedIds.Contains(p.Id) });
}
public IEnumerable<ApplicantBranchItem> Items { get; set; }
}
ApplicantBranchList
有其自己的编辑器模板,以及ApplicantBranchList
中每个项目的内部编辑器模板:视图/共享/EditorTemplates/ApplicantBranchList.cshtml:
@model Comair.RI.UI.Models.ApplicantBranchList
<table>
<tr>
<th style="display: none;"></th>
<th>
@Html.DisplayNameFor(model => model.HeaderItem.BranchName)
</th>
<th>
@Html.DisplayNameFor(model => model.HeaderItem.WillWorkAt)
</th>
</tr>
@foreach (var item in Model.Items)
{
@Html.EditorFor(m => item)
}
</table>
视图/共享/EditorTemplates/ApplicantBranchItem.cshtml:
@model Comair.RI.UI.Models.ApplicantBranchItem
<tr>
<td style="display: none;">
@Html.HiddenFor(m => m.BranchId)
</td>
<td>
@Html.DisplayFor(m => m.BranchName)
</td>
<td>
@Html.EditorFor(m => m.WillWorkAt)
</td>
</tr>
该编辑器可以在视图中正确显示,但在后期操作中:
public ActionResult Create(ApplicantProfileModel model)
{
if (ModelState.IsValid)
{
var branches = model.PreferedBranches;
PreferedBranches.Items
是null
。我究竟做错了什么?
最佳答案
问题是ASP.NET无法弄清楚如何绑定到Model.Items
属性。
要修复它,请替换:
public IEnumerable<ApplicantBranchItem> Items { get; set; }
有了这个:
public List<ApplicantBranchItem> Items { get; set; }
而不是:
@foreach (var item in Model.Items)
{
@Html.EditorFor(m => item)
}
使用这个:
@for (var i = 0; i < Model.Items.Count; i++)
{
@Html.EditorFor(model => model.Items[i]) // binding works only with items which are accessed by indexer
}