这是我的编辑器模板,用于显示固定的省份列表,每个省份都有一个复选框:
@model Comair.RI.UI.Models.ApplicantRelocateProvinceList
<table>
<tr>
<th style="display: none;"></th>
<th>
@Html.DisplayNameFor(model => model.HeaderItem.Province)
</th>
<th>
@Html.DisplayNameFor(model => model.HeaderItem.WillRelocate)
</th>
</tr>
@foreach (var item in Model.Items)
{
@Html.EditorFor(m => item)
}
</table>
这是Model.Items
类型模型的编辑器模板:
@model Comair.RI.UI.Models.ApplicantRelocateProvinceItem
<tr>
<td style="display: none;">
@Html.HiddenFor(m => m.Id)
</td>
<td>
@Html.DisplayFor(m => m.Province.Name)
</td>
<td>
@Html.EditorFor(m => m.WillRelocate)
</td>
</tr>
我已经成功地将这个模型用于其他视图模型。这是ApplicantRelocateProvinceList
模型:
public class ApplicantRelocateProvinceList : ViewModel
{
public ApplicantRelocateProvinceItem HeaderItem { get; set; }
public ApplicantRelocateProvinceList()
{
HeaderItem = new ApplicantRelocateProvinceItem();
}
public void MapFromEntityList(IEnumerable<ApplicantRelocateProvince> applicantProvinces)
{
var service = new ProvinceService(DbContext);
var selectedIds = applicantProvinces.Select(ap => ap.ProvinceId);
Items = service.ReadProvinces()
.Where(i => !i.IsDeleted)
.Select(p => new ApplicantRelocateProvinceItem {Id = p.Id, Province = p, WillRelocate = selectedIds.Contains(p.Id)});
}
public IEnumerable<ApplicantRelocateProvinceItem> Items { get; set; }
}
此代码读取我们九个省份的固定列表,以及申请人选择的可变省份列表。那些ID在申请者所在省份的固定省份被标记WillRelocate
为真,以显示其复选框为选中状态。