asp.net mvc:为什么 Html.CheckBox 生成额外的隐藏输入 [英] asp.net mvc: why is Html.CheckBox generating an additional hidden input

查看:17
本文介绍了asp.net mvc:为什么 Html.CheckBox 生成额外的隐藏输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到 Html.CheckBox("foo") 生成 2 个输入而不是一个,有人知道为什么会这样吗?

I just noticed that Html.CheckBox("foo") generates 2 inputs instead of one, anybody knows why is this so ?

<input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" /> 

推荐答案

如果未选中复选框,则不提交表单域.这就是隐藏字段中总是存在错误值的原因.如果您未选中复选框,表单仍将具有隐藏字段中的值.这就是 ASP.NET MVC 处理复选框值的方式.

If checkbox is not selected, form field is not submitted. That is why there is always false value in hidden field. If you leave checkbox unchecked, form will still have value from hidden field. That is how ASP.NET MVC handles checkbox values.

如果您想确认这一点,请不要使用 Html.Hidden,而是使用 <input type="checkbox" name="MyTestCheckboxValue"></input> 在表单上放置一个复选框.取消选中复选框,提交表单并查看服务器端发布的请求值.您会看到没有复选框值.如果您有隐藏字段,它将包含带有 false 值的 MyTestCheckboxValue 条目.

If you want to confirm that, place a checkbox on form not with Html.Hidden, but with <input type="checkbox" name="MyTestCheckboxValue"></input>. Leave checkbox unchecked, submit form and look at posted request values on server side. You'll see that there is no checkbox value. If you had hidden field, it would contain MyTestCheckboxValue entry with false value.

这篇关于asp.net mvc:为什么 Html.CheckBox 生成额外的隐藏输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆