2

I often use the built in CheckBox HtmlHelper as it allows me to easily specify the checked state of the element like this

@Html.CheckBox("Test",Model.IsChecked);

vs creating it on the view like so

@if(Model.IsChecked)
{
  <input id="test" type="checkbox" checked="checked" />
}
else
{
  <input id="test" type="checkbox"  />
}

However when inspecting the html generated by the helper i can see it renders this html.

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

I can't work out why there is a hidden field input as well, what is it used for?

1 Answer 1

3

Form data submitted by the browser does not include keys and values for unchecked checkboxes. Without the hidden field, there is no way for the server-side code to determine if the checkbox is present in the form and is unchecked or if it does not exist on the client at all.

Html.CheckBox creates hidden field with the same name as the name of the input with type="checkbox", therefore the submitted value is "true,false" for checked checkbox, and "false" for unchecked checkbox.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.