简体   繁体   English

使用Razor的POST上Model.List为null

[英]Model.List is null on POST using Razor

My view: 我的看法:

@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 })
  <label>@item.Name</label>
}

My controller: 我的控制器:

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

Model.List is null? Model.List为空?

The list populates okay on GET . 可以在GET上填充列表。 However, on POST (this particular View is a form) Model.List is null. 但是,在POST (此特定的View是一种表单)上, Model.List为null。 I've tried using the HiddenFor helper, but have not yet succeeded. 我曾尝试使用HiddenFor帮助器,但尚未成功。

Any suggestions / answers are appreciated. 任何建议/答案表示赞赏。 Thanks. 谢谢。

You need to use a for loop instead of a foreach loop for data binding to work correctly with collections. 您需要使用for循环而不是foreach循环来进行数据绑定,才能正确使用集合。

So instead of doing a foreach loop, change your code to something like this: 因此,不要执行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 })
  <label>@Model.List[i].Name</label>
}

This enables the ModelBinder to track the index of the item in your collection you're trying to bind. 这使ModelBinder可以跟踪您要绑定的集合中项目的索引。

If you look at the generated HTML when you have done this, you will notice that the generated input controls will look something like this: 如果在完成此操作后查看生成的HTML,您会注意到生成的输入控件将如下所示:

<input type="hidden" name="List[0].IsChecked" />

This enables the model binder to know to which item in the list, it is binding to. 这使模型绑定程序可以知道列表绑定到的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM