tags:

views:

137

answers:

1

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.

+2  A: 

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');
}
David Liddle
David, thanks. I have discovered that this is done to overcome the fact that the browser will not post back a value to the server if the checkbox is not checked. I will just need to alter my thinking here because my form data had been binding very nicely to my strongly-typed SearchCriteria object before I added the checkbox. Now I will need to loop through the FormCollection object to retrieve the values and manually transfer the values to my SearchCriteria object.
Rich