Html.CheckBox in MVC

The CheckBox helper is unique because it renders two input elements. Take the following code, for example:

@Html.CheckBox("IsDiscounted")

This code produces the following HTML:

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

You are probably wondering why the helper renders a hidden input in addition to the checkbox input. The helper renders two inputs because the HTML specification indicates that a browser will submit a value for a checkbox only when the checkbox is on (selected). In this example, the second input guarantees a value will appear for Is Discounted even when the user does not check the checkbox input.
Although many of the helpers dedicate themselves to building forms and form inputs, helpers are available that you can use in general rendering scenarios.

Tagged . Bookmark the permalink.

Leave a Reply