Map Your Checkboxes To bool MVC Action Parameters

by Matt 1. February 2010 20:40

Over the past couple of months, I've decided I no longer like accepting a FormCollection object in post actions in my MVC applications.  I've decided to strongly type my parameters for easier debugging and, well, it's resulted in a whole lot fewer casts in my code.  It just makes sense.  

This worked quite well with most datatypes, but booleans mapped to a checkbox presented an interesting case.  While a checked check box posts true, an unchecked one posts null.
The solution was to make the boolean nullable.  I can't think of any better solution but I think this approach is fairly elegant.  See the example below.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(string Param1, string Param2, bool? Param3)
{
// code...
}

Tags:
Categories: ASP.NET | MVC