ASP.NET MVC 2 - 复选框
我使用 string[] Roles = Roles.GetAllRoles()
来获取我的应用程序的所有 ASP.NET 成员角色的 string[]。我将角色发送到 ViewData 中的视图,并使用 foreach 创建一组复选框(使用 <%: Html.CheckBox("RoleCheckBox") %>
)。有 3 个角色,我的视图确实呈现 3 个复选框。当我执行“查看/源”操作时,我会看到复选框及其相应的隐藏标签。它们都有相同的内容,因此有 6 个名为“RoleCheckBox”的标签 - 3 个呈现复选框,3 个隐藏。
当我将表单发回控制器并绑定结果时,问题就出现了 - 类似 public ActionResult Create(Person person, string[] RoleCheckBox)
。我得到四个字符串,但我不知道第四个字符串(“假”)来自哪里。我可以通过尝试各种检查组合来进行一些测试,看看哪一个(希望)不会改变并忽略它,但这只是丑陋的。
有谁知道为什么会发生这种情况?
谢谢,
杰伊
I'm using string[] roles = Roles.GetAllRoles()
to get a string[] of all the ASP.NET membership roles for my application. I'm sending the roles to my view in ViewData and using a foreach to create a set of Checkboxes using <%: Html.CheckBox("RoleCheckBox") %>
. There are 3 roles and my view does render 3 checkboxes. When I do a View/Source, I see the checkboxes and their corresponding hidden tags. They all have the same, so there are 6 tags with the name "RoleCheckBox" - 3 that render the checkboxes and 3 that are hidden.
The problem comes when I post the form back to my controller and bind the results - something like public ActionResult Create(Person person, string[] RoleCheckBox)
. I get FOUR strings and I have no idea where the fourth string ("false") is coming from. I could do some testing by trying various combinations of checks to see which one (hopefully) doesn't change and ignore it but that's just ugly.
Does anyone know why this would be happening?
Thanks,
Jay
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
额外的“假”是因为选中复选框时会产生一对(数组),例如“真,假”。第二个错误来自隐藏值。如果未选中,则不会获得第一个值,因为该复选框不会返回任何内容。
此链接更详细地解释了它,并建议循环遍历表单键并使用“ GetValues()”在每个元素上,然后获取结果数组中的第一个元素。
The extra "false" comes because there are a pair (array) produced when the checkbox is checked, e.g. "true,false". The second false is coming from the hidden value. If it is not checked you get no first value because the checkbox returns nothing.
This link explains it in more detail and recommends to loop through the form keys and use "GetValues()" on each element and then get the first element in the resulting array.