@Html.HiddenFor 不适用于 ASP.NET MVC 中的列表 [英] @Html.HiddenFor does not work on Lists in ASP.NET MVC
问题描述
我正在使用一个包含 List 作为属性的模型.我正在使用从 SQL Server 中获取的项目填充此列表.我希望列表隐藏在视图中并传递给 POST 操作.稍后我可能想使用 jQuery 向此列表添加更多项目,这使得数组不适合稍后扩展.通常你会使用
I'm using a model that contains a List as a property. I'm populating this list with items i grab from SQL Server. I want the List to be hidden in the view and passed to the POST action. Later on i may want to add more items to this List with jQuery which makes an array unsuitable for expansion later on. Normally you would use
@Html.HiddenFor(model => model.MyList)
为了完成这个功能,但是由于某种原因,POST 中的 List 始终为空.
to accomplish this functionality, but for some reason the List in POST is always null.
很简单的问题,有人知道MVC为什么会这样吗?
Very simple question, anyone know why MVC behaves like this?
推荐答案
我刚刚遇到这个问题并通过执行以下操作简单地解决了它:
I've just come across this issue and solved it simply by doing the following:
@for(int i = 0; i < Model.ToGroups.Count; i++)
{
@Html.HiddenFor(model => Model.ToGroups[i])
}
通过使用 for
而不是 foreach
模型绑定将正常工作并获取列表中的所有隐藏值.似乎是解决这个问题的最简单方法.
By using a for
instead of a foreach
the model binding will work correctly and pick up all of your hidden values in the list. Seems like the simplest way to solve this problem.
这篇关于@Html.HiddenFor 不适用于 ASP.NET MVC 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!