我的看法:
@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>
}
我的 Controller :
[HttpPost]
public ActionResult Create(MyModel Model)
{
..
Model.List
为空?
列表在 GET
上正常填充。但是,在 POST
(这个特定的 View 是一个表单)上,Model.List
为空。我试过使用 HiddenFor
助手,但还没有成功。
如有任何建议/答案,我们将不胜感激。谢谢。
最佳答案
您需要使用 for
循环而不是 foreach
循环,数据绑定(bind)才能正确处理集合。
因此,不要执行 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>
}
这使 ModelBinder 能够跟踪您尝试绑定(bind)的集合中项目的索引。
如果您在完成此操作后查看生成的 HTML,您会注意到生成的输入控件看起来像这样:
<input type="hidden" name="List[0].IsChecked" />
这使模型绑定(bind)器知道它绑定(bind)到列表中的哪个项目。
关于c# - Model.List 在使用 Razor 的 POST 上为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25159796/