In my quest to get my wpfstyle.com site written in the new ASP.Net MVC framework (day 3) I’ve run across a little issue that I’m sure will come up again.
In my world, a checkbox always seemed to imply true/false or yes/no. In reality, it can mean a lot of things in an Html Form. It’s an input, remember, and inputs have a value. When your checkbox is checked, that value is posted back.
Making it work as a boolean indicator in your MVC application, is possible though. In keeping with the Membership/Authorization theme from yesterday, I have the following controller action:
public void Authenticate(string userName, string password, bool? rememberMe)
[Hint: Notice the '?' after bool for the third parameter. That'll be important in a moment.]
Here is the corresponding Login.aspx View which contains a form posting to this action:
<%using (Html.Form("Authenticate", "Account")) { %> <div style="margin: auto auto 4px auto">Username <%=Html.TextBox( "username") %> </div> <div style="margin: auto auto 4px auto">Password <%=Html.Password( "password") %></div> <div style="margin: auto auto 4px auto"> <%=Html.CheckBox("rememberme", "Remember Me", "true", false)%> </div><div><%=Html.SubmitButton( "Log In") %></div> <%} %>
Looking at our intellisense for Html.Checkbox, we see
By setting the checkbox’s value to “true” we’re going to have that value sent back through the MVC pipeline to our Action which has a boolean parameter rememberme. It’s not just any boolean though, it’s a nullable boolean. Remember when I meantion the distinction that the checkbox being checked causes the value to be posted back? Well if the checkbox is *not* checked, the rememberme value will be null.
The MVC pipeline is nice enough to implicitly convert the “true” string to a boolean, but null is not necessarily false in all cases. To account for this, we must make our parameter a nullable boolean. Does this maybe cross the line into mixing UI and Controller… eh – possibly?
(NOTE: If you don’t see the Checkbox method in your intellisense, make sure you picked up and referenced the MVC Toolkit)

I have been reading comments here and thought I would finally sign up so I could post a comment now and then.
Karen:)