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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With