使用Razor在POST上使用Model.List为null

我的看法:

@foreach(var item in Model.List) { @Html.HiddenFor(model => item.UserId) @Html.HiddenFor(model => item.Name) @Html.HiddenFor(model => item.Age) @Html.CheckBoxFor(model => item.IsChecked, new { id = item.UserId })  } 

我的控制器:

 [HttpPost] public ActionResult Create(MyModel Model) { .. 

Model.List为null?

该列表在GET上填充正常。 但是,在POST (此特定View是一个表单) Model.List为null。 我尝试过使用HiddenFor助手,但还没有成功。

任何建议/答案都表示赞赏。 谢谢。

您需要使用for循环而不是foreach循环来使数据绑定与集合一起正常工作。

因此,不要执行foreach循环,而是将代码更改为以下内容:

 @for (var i = 0; i < Model.List.Count(); i++) { @Html.HiddenFor(model => Model.List[i].UserId) @Html.HiddenFor(model => Model.List[i].Name) @Html.HiddenFor(model => Model.List[i].Age) @Html.CheckBoxFor(model => Model.List[i].IsChecked, new { id = Model.List[i].UserId })  } 

这使得ModelBinder可以跟踪您尝试绑定的集合中项目的索引。

如果您在完成此操作时查看生成的HTML,您会注意到生成的输入控件将如下所示:

  

这使模型绑定器能够知道列表中绑定的项目。