我已经在网上进行了研究,但希望有人可以帮助我。
我有以下 ViewModel 类:
public class PersonEditViewModel
{
public Person Person { get; set; }
public List<DictionaryRootViewModel> Interests { get; set; }
}
public class DictionaryRootViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<DictionaryItemViewModel> Items;
public DictionaryRootViewModel()
{
Items = new List<DictionaryItemViewModel>();
}
}
public class DictionaryItemViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
在编辑视图中,我使用自定义 EditorTemplate 来布局使用@Html.EditorFor(m => m.Interests)
. 有两个执行渲染的 EditorTemplate:
DictionaryRootViewModel.cshtml:
@model Platforma.Models.DictionaryRootViewModel @Html.HiddenFor(model => model.Id) @Html.HiddenFor(model => model.Name) @Html.EditorFor(model => model.Items)
DictionaryItemViewModel.cshtml:
@model Platforma.Models.DictionaryItemViewModel @Html.HiddenFor(model => model.Id) @Html.CheckBoxFor(model => model.Selected) @Html.EditorFor(model => model.Name)
问题:
使用 POST 提交表单时,仅Interests
填充集合并且Interest.Items
集合始终为空。该请求包含(除其他外)以下字段名称,它们在控制器操作方法中检查 Request.Forms 数据时也会出现。
- 兴趣[0].Id
- 兴趣[0].姓名
- 兴趣[0].Items[0].Id
- 兴趣[0].Items[0].Selected
都包含正确的值 - 但在控制器端,方法中的对象 pvm:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonEditViewModel pvm)
{
}
包含 Interests 集合中的数据(具有正确 id 和名称的项目),但对于集合的每个元素,它的 Items 子集合是空的。
我如何才能正确选择模型?