Say you have some controller action that takes a boolean:
public ActionResult Login(string username, string password, bool rememberMe)
{
// authenticate...
}
Now, you want to let the user set the “Remember me?” option using a check box:
<input type="checkbox" id="rememberMe" name="rememberMe" />
<label for="rememberMe">Remember me?</label>
This won’t work! A checkbox is an input element, so when it gets posted, it posts its value - and a checkbox has the value ‘on’ by default (which cannot be parses as a boolean). You might think that we could use a bit of JavaScript trickery to change the value depending on the checked/unchecked state:
<input type="checkbox" id="rememberMe" name="rememberMe"
onchange="this.value = this.checked ? 'true' : 'false'" />
<label for="rememberMe">Remember me?</label>
This won’t work either! 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. This means that for an unchecked checkbox, ASP.NET MVC will not be able to find a value to map to the rememberMe parameter, and thus throw an exception at you.
The best way then to map a checkbox to a boolean action parameter, is to just set the value of the checkbox to ‘true’ (since it will only ever be used when the checkbox is checked):
<input type="checkbox" id="rememberMe" name="rememberMe" value="true" />
<label for="rememberMe">Remember me?</label>
and then use a nullable boolean as the controller action parameter:
public ActionResult Login(string username, string password, bool? rememberMe)
{
// authenticate...
}
This way, you'll get a 'null' when "Remember me?" is unchecked, and true when it is checked.