c# - Model.List 在使用 Razor 的 POST 上为空

标签 c# asp.net-mvc

我的看法:

@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/

相关文章:

c# - 如何从对象列表创建 MVC HtmlHelper 表

c# - 如何使用 Hangfire 获取失败的后台作业的异常详细信息

c# - 子任务取消,父任务完成?

c# - 传递给 Controller ​​时,具有复杂类型的 View 模型为空

asp.net-mvc - ASP.NET MVC : Returning a view with querystring intact

c# - 用于常见操作的 C# 属性的有序列表?

c# - 使用Nest + C#在 Elasticsearch 中查找具有空字段/附件的文档

c# - 如何在长时间运行的功能期间更新 UI(文本字段)?

c# - WriteOnly属性还是方法?

JQuery Ajax 调用给出 404 'Resource Not Found' 错误,但正常的 URL 调用没问题