40

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
tugberk
  • 57,477
  • 67
  • 243
  • 335

3 Answers3

51

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
  • 3,907
  • 1
  • 30
  • 35
  • 2
    so that means, this checkbox will be passed as false to the controller? – tugberk Mar 28 '11 at 18:01
  • Only if the box is not checked. If it's checked, it will be bound with true. Give it a try with the debugger. Also, try it without the HTML Helper and you can see why they made it that way. – ericvg Mar 28 '11 at 18:04
  • so as I understood, the hidden field value turns out true if checkbox is checked and the controller gets the value of hidden field after that. am I following you here right? – tugberk Mar 28 '11 at 19:27
  • 2
    No, the hidden value will _always_ be false and is _always_ posted. If the box is checked, a true is also posted and the model binder uses the true value. This is a common question, so you might want to google around a bit if you still don't understand or simply look at the mvc source code. – ericvg Mar 28 '11 at 19:45
  • @ericvg thanks a lot for your help. I'll dig into mvc source code when I got a time. – tugberk Mar 28 '11 at 19:48
  • 1
    No problem -- here is another SO answer that might explain it better: http://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional-hidden-input – ericvg Mar 28 '11 at 19:54
  • great :) the good point is that it will work easily with AJAX – Hovhannes Babayan Oct 27 '15 at 07:04
3

ericvg explained it well.

The manual approach is this:

bool IsDefault = (Request.Form["IsDefault"] != "false");
Valamas
  • 24,169
  • 25
  • 107
  • 177
3

Or use Contains("true") which I find a bit neater...

bool myCheckBoxValue = Server.HtmlEncode(Request.QueryString["MyCheckBoxValue"]).Contains("true");
pfeds
  • 2,183
  • 4
  • 32
  • 48