0

我已经在网上进行了研究,但希望有人可以帮助我。

我有以下 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:

  1. DictionaryRootViewModel.cshtml:

    @model Platforma.Models.DictionaryRootViewModel
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Name)
    @Html.EditorFor(model => model.Items)
    
  2. 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 子集合是空的。

我如何才能正确选择模型?

4

2 回答 2

2

像往常一样——答案一直摆在我面前。DefaultModelBinder 没有获取请求中传递的 Items 值,因为我“忘记”将 Items 集合标记为属性 - 它是一个字段!考虑到@pjobs 的有用评论的正确形式:

public List<DictionaryItemViewModel> Items{获取;设置;}

于 2015-04-22T15:26:19.060 回答
0

大多数情况下,问题在于索引,当您发布收藏集时,您要么需要有顺序索引,要么如果索引不是顺序的,则需要有 Interests[i].Items.Index 隐藏字段。

这是关于SO的类似问题

如果您有,它将无法正常工作

Interests[0].Id
Interests[0].Name
Interests[0].Items[0].Id
Interests[0].Items[0].Selected
Interests[0].Items[2].Id
Interests[0].Items[2].Selected

因此,要修复它,您要么确保将顺序索引设置为

Interests[0].Id
Interests[0].Name
Interests[0].Items[0].Id
Interests[0].Items[0].Selected
Interests[0].Items[1].Id
Interests[0].Items[1].Selected

或者

Interests[0].Id
Interests[0].Name
Interests[0].Items.Index = 0 (hidden field)
Interests[0].Items[0].Id
Interests[0].Items[0].Selected
Interests[0].Items.Index = 2 (hidden field)
Interests[0].Items[2].Id
Interests[0].Items[2].Selected
于 2015-04-22T14:03:14.817 回答