asp.net - 将复选框组存储在@Html.HiddenFor中

标签 asp.net asp.net-mvc

在一个 View 中,我有一组映射到 List<int> 的复选框。 。

查看:

<input name="foo.IntegerList" type="checkbox" value="1"> 
<input name="foo.IntegerList" type="checkbox" value="2"> 
<input name="foo.IntegerList" type="checkbox" value="3"> 
<input name="foo.IntegerList" type="checkbox" value="4"> 
<input name="foo.IntegerList" type="checkbox" value="5"> 

行动:

[HttpPost]
<public ActionResult DoStuff(Foo foo)
    //do stuff

型号:

public class Foo
{
    IEnumerable<int> IntegerList
}

将此表单帖子提交到 DoStuff 操作会为其填充 List<int>

现在,我必须使用IntegerList在另一个 View 中,并作为隐藏字段。在另一个 View 中,我使用以下代码:

@Html.HiddenFor(p => p.IntegerList)

但这会被翻译为以下 HTML:

<input name="IntegerList" type="hidden" value="">

请注意,该值尚未设置。我该如何制作Html.HiddenFor生成正确的隐藏字段?

最佳答案

您必须迭代它们并将名称与索引放在一起:

@for(int i = 0; i < Model.IntegerList.Count; i++)
    <input name="IntegerList[@i]" type="hidden" value="@Model.IntegerList[i]">
}

使用 HiddenFor 就可以这样完成

@for(int i = 0; i < Model.IntegerList.Count; i++)
    @Html.HiddenFor(model => Model.IntegerList[i])
}

关于asp.net - 将复选框组存储在@Html.HiddenFor中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405617/

相关文章:

c# - 如何限制用户登录?

c# - 用 XML 编写命名空间

asp.net-mvc - 在复选框选择上启用/禁用 'DropDownListFor'

c# - 模型验证在单元测试中不起作用

javascript - 当客户端 onblur 事件被触发并返回 false 时,如何取消文本框的服务器端 OnTextChanged 事件?

c# - 如何使用 System.Threading 模拟下载速度

asp.net - 将 rtl 样式与 TreeView 一起使用时出现水平滚动条问题

c# - 记录级授权的 MVC/ASP.Net 最佳实践

c# - asp.net mvc 中的区域,一次只能工作一个

c# - 复杂模型/子模型验证 (MVC) 的最佳方法