C# ASP.NET MVC5模型绑定器-绑定集合集合时为空
我已经在网上搜索过了,希望这里有人能帮我 我有以下ViewModel类:C# ASP.NET MVC5模型绑定器-绑定集合集合时为空,c#,asp.net-mvc,razor,defaultmodelbinder,C#,Asp.net Mvc,Razor,Defaultmodelbinder,我已经在网上搜索过了,希望这里有人能帮我 我有以下ViewModel类: public class PersonEditViewModel { public Person Person { get; set; } public List<DictionaryRootViewModel> Interests { get; set; } } public class DictionaryRootViewModel { public long Id { get;
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; }
}
@model Platforma.Models.DictionaryRootViewModel
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Name)
@Html.EditorFor(model => model.Items)
@model Platforma.Models.DictionaryItemViewModel
@Html.HiddenFor(model => model.Id)
@Html.CheckBoxFor(model => model.Selected)
@Html.EditorFor(model => model.Name)
兴趣
集合,并且兴趣.项目
集合始终为空。
请求包含(除其他外)以下字段名,它们在检查控制器操作方法中的request.Forms数据时也存在
- 兴趣[0]。Id
- 兴趣[0]。名称
- 兴趣[0]。项目[0]。Id
- 兴趣[0]。项目[0]。已选定
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonEditViewModel pvm)
{
}
包含兴趣集合中的数据(具有正确id和名称的项),但对于集合的每个元素,其项的“子集合”为空
如何正确选择模型?大多数情况下,问题在于索引,当您发布集合时,您需要有顺序索引,或者需要有兴趣[I].Items.index隐藏字段(如果索引不是顺序的) 如果你有,它将不起作用
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
和往常一样,答案一直摆在我面前。 DefaultModelBinder没有拾取请求中传递的Items值,因为我“忘记”将Items集合标记为属性-它是一个字段! 考虑到@pjobs的有用评论的正确形式:
公共列表项
{get;set;}不太熟悉mvc,但可能您的模型必须是[可序列化]?您好,谢谢您的帮助!不幸的是,它似乎不起作用。第一种方法已经实现,因为我正在使用ASP.NET MVC5的内置模板功能。我尝试了另一个,结果是一样的。我们可以从您的回发中看到更多信息吗,我是指您请求的所有内容。表单数据另一件事是您可以在ViewModel中将公共ICollection项更改为公共列表项吗?请尝试,从ICollection更改为列表项没有帮助。请求中的所有字段都位于此处:。你可以看到更多的收藏——所有的收藏都以与兴趣收藏相同的方式失败。哇,那是很多收藏,你是从张贴的表格中得到的。。。?非常大的形式:),我认为这只是简写,应该指出它