CheckboxStandard and BoolBinder Tutorial

This tutorial aims to illustrate the use of the CheckboxStandard HtmlHelper and why you may want to use it instead of the normal MVC Checkbox HtmlHelper. The CheckboxStandard HtmlHelper (and the BoolBinder) you use with it is found in the DigitallyCreated.Utilities.Mvc assembly. The CheckboxStandard extension method is found in the FormHtmlHelpers class. The tutorial assumes you are familiar with C# and ASP.NET MVC.

You may not have noticed, but the standard Checkbox HtmlHelper does not just emit an input tag with type "checkbox". This is what it emits:

<input checked="checked" id="MyCheckbox" name="MyCheckbox" type="checkbox" value="true" />
<input name="MyCheckbox" type="hidden" value="false" />

See that extra hidden field? MVC inserts that in there so that if you untick the checkbox (and no value is send in the form submit), a value is actually sent: the value of "false". This is so that is can distinguish between a missing value (null) and an unticked checkbox (supposedly false).

This makes sense, but what happens if we don't want this? For example, if our form's method is set to GET instead of POST, we may want that value to be missing, so we get a cleaner URL:

http://www.mysite.com/Controller/Action
instead of
http://www.mysite.com/Controller/Action?MyCheckbox=false

If this is something that you desire, the CheckboxStandard HtmlHelper can do that for you. Here's an example of its use:

In the View
<% using (Html.BeginForm(null, null, FormMethod.Get)) { %>
    <table class="LayoutTable">
        <tr>
            <td>
                <label for="MyCheckbox">My Checkbox:</label>
            </td>
            <td>
                <%= Html.CheckboxStandard("MyCheckbox") %>
            </td>
        </tr>
    </table>
<% } %>

In the Controller
public ActionResult Action([ModelBinder(typeof(BoolBinder))] bool myCheckbox)
{
    //Your action code here
}

Note the use of the custom model binder BoolBinder on the myCheckbox parameter on the action method. Without this, the lack of a "MyCheckbox=false" on the URL will cause MVC to try to bind null to bool, obviously causing a fail (since bool is a value type). The BoolBinder takes the lack of a MyCheckbox URL parameter to mean "false".

Last edited Mar 23, 2010 at 6:14 AM by dchambers, version 2

Comments

No comments yet.