Pro*_*ofK 9 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
我有一个模型,ApplicantBranchList在大型模型中用作属性,如下所示:
[Display(Name = "Where would you want to work?")]
public ApplicantBranchList PreferedBranches { get; set; }
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
查看/共享/ 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>
Run Code Online (Sandbox Code Playgroud)
此编辑器在视图中正确呈现,但在后期操作中:
public ActionResult Create(ApplicantProfileModel model)
{
if (ModelState.IsValid)
{
var branches = model.PreferedBranches;
Run Code Online (Sandbox Code Playgroud)
PreferedBranches.Items是null.
我究竟做错了什么?
SHS*_*HSE 14
问题是ASP.NET无法弄清楚如何绑定到Model.Items属性.
要修复它替换:
public IEnumerable<ApplicantBranchItem> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)
有了这个:
public List<ApplicantBranchItem> Items { get; set; }
Run Code Online (Sandbox Code Playgroud)
而不是:
@foreach (var item in Model.Items)
{
@Html.EditorFor(m => item)
}
Run Code Online (Sandbox Code Playgroud)
使用这个:
@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
}
Run Code Online (Sandbox Code Playgroud)
ken*_*der 12
使用MVC和编辑器模板,您无需手动浏览列表并调用@HTMLEditorFor.
这样做:
@Html.EditorFor(model => model.Items)
Run Code Online (Sandbox Code Playgroud)
是相同的:
@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
}
Run Code Online (Sandbox Code Playgroud)
MVC将处理项目的迭代,并为每个项目生成一次编辑器模板.如评论中所述,您的模板必须与您的模型命名相同.此外,您的模型定义应该是模型的单一表示,而不是IEnumerable类型.最后,如评论中所述,如果在调用@ Html.EditorFor()时指定模板名称参数,则不会对集合进行自动迭代.您将需要手动迭代,如上所示.