开发者

Why does a checkbox also have a hidden tag with it? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

asp.net mvc: why is Html.CheckBox generating an additional hidden input

I'm rendering a checkbox in an asp.net mvc app, and the control is also outputting a hidden field like this:

<input id="blah-64" name="blah-64" value="true" type="checkbox">
<input name="blah-64"开发者_开发百科 value="false" type="hidden">

Problem is, when I post the form, the form key "blah-64 returns "on, off".

Why is this?


If you look at the source code for the Checkbox helper you'll see a comment that explains it. It looks like this:

if (inputType == InputType.CheckBox) { 
    // Render an additional <input type="hidden".../> for checkboxes. This 
    // addresses scenarios where unchecked checkboxes are not sent in the request. 
    // Sending a hidden input makes it possible to know that the checkbox was present 
    // on the page when the request was submitted. 
...

This is because the W3C specification says that, "When a form is submitted, only "on" checkbox controls can become successful." (Successful being their term for the value submitted). The hidden field ensures they are submitted, regardless of whether they are checked or not. If you don't want this behaviour then simplest way is to render the HTML yourself and don't use a helper.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜