This question already has an answer here:
-
asp.net mvc: why is Html.CheckBox generating an additional hidden input
9 answers
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?
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
ericvg explained it well.
The manual approach is this:
bool IsDefault = (Request.Form["IsDefault"] != "false");
Or use Contains("true") which I find a bit neater...
bool myCheckBoxValue = Server.HtmlEncode(Request.QueryString["MyCheckBoxValue"]).Contains("true");