Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor ViewEngine HTML.Checkbox method creates a hidden input. Why? [duplicate]

I have written the below code on my view page;

@Html.CheckBox("ChxName",true) 

and I got the following result;

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

why is there a input element named as the same with checkbox?

like image 399
tugberk Avatar asked Mar 28 '11 17:03

tugberk


People also ask

Why is HTML checkbox generating an additional hidden input?

CheckBox is generating an additional hidden field with a false value. It is because, when you not select a checkbox, still form sends a false value to the server.

How do I make a checkbox in razor?

Razor offers two ways to generate checkboxes. The recommended approach is to use the input tag helper. Any boolean property of the PageModel will render a checkbox if it is passed to the asp-for attribute, so long as the property is not nullable: public class IndexModel : PageModel.


1 Answers

Unchecked checkboxes are not posted, so the hidden field (set as false) allows the model binding to still work.

Look at Request.Form on the post back. If the checkbox is checked, you'll see:

ChxName=true&ChxName=false 

The model binder uses the first value.

and, if the box isn't checked, you'll see:

ChxName=false 
like image 89
ericvg Avatar answered Oct 02 '22 18:10

ericvg