Tôi đã một mô hình, ApplicantBranchList
, được sử dụng như một tài sản trong một mô hình lớn hơn như sau:Làm cách nào để làm cho mẫu trình chỉnh sửa dựa trên danh sách của tôi được ràng buộc đúng cách cho một hành động POST?
[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
có mẫu biên tập của riêng mình, và mẫu trình chỉnh sửa bên trong cho mỗi mục trong ApplicantBranchList
:
Views/Shared/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>
Views/Shared/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>
biên tập này làm cho đúng cách trong giao diện , nhưng trong hành động sau:
public ActionResult Create(ApplicantProfileModel model)
{
if (ModelState.IsValid)
{
var branches = model.PreferedBranches;
PreferedBranches.Items
là null
.
Tôi đang làm gì sai?
Giải pháp này hoạt động khi bạn cần chỉ định tên Mẫu. – MichaelLake