My view page contains a search-by-example form with the following checkbox code:
<td> <label for='HasProcessErrors'>Has Errors:</label> <%= Html.CheckBox('HasProcessErrors', crit.HasProcessErrors) %> </td>
The crit object HasProcessErrors property is a boolean whose initial value is false. When I view the source of my rendered page, I see that the helper has generated the following HTML:
<td> <label for='HasProcessErrors'>Has Errors:</label> <input id='HasProcessErrors' name='HasProcessErrors' type='checkbox' value='true' /><input name='HasProcessErrors' type='hidden' value='false' /> </td>
Have I used the CheckBox helper incorrectly here, or is something odd going on? It seems like it should generate an input of type checkbox with checked = ”.
Thanks for any ideas.
Yes this is correct.
The semantics of a checkbox are a little bit different from what you may think; instead of posting a value indicating its checked/unchecked state, a checked checkbox posts whatever is in its ‘value’ attribute, and an unchecked checkbox posts nothing.
As there is also a hidden field with the same name, if you debug your form submit, you will find a checked checkbox has the value ‘true,false’ whilst an unchecked box has the value ‘false’
You can determine if a checkbox is checked by testing if it contains ‘true’.
public ActionResult(FormCollection form) { bool checked = form['checkbox_id'].ToString().Contains('true'); }