Monday, August 25, 2008

ASP.NET MVC HtmlHelper and CheckBoxExtensions (Html.CheckBox)

I've been working with Preview 3 of ASP.NET MVC, and started working with the HtmlHelper class.

These are the methods for generating an HTML controls with the HtmlHelper class. Very useful for developing view, entry, and edit views.

This is a short (and incomplete) list of some of the methods available for generating html controls:
string ActionLink - Generate html link to an action
string AttributeEncode - Html encode attribute
string DropDownList - Html dropdown list
string Encode - Html encode value
string Hidden - Html input of type hidden
string ListBox - Html listbox
string Password - Html input of type password
string RouteLink - Link to a specific route
string TextBox - Html input
string CheckBox [Extension method from System.Web.Mvc.CheckBoxExtensions]
string TextArea [Extension method from System.Web.Mvc.TextInputExtensions]

This article is specifically about the CheckBox extension method, and how to use it.

The CheckBox extension method are contained within the
CheckBoxExtensions class located in the System.Web.Mvc namespace.

There were a number of posts out there about using a boolean value, and having that value correctly transformed back into a boolean using the BindingHelperExtensions.

The trick to correctly using this control for this purpose, is to set the value to "true", and to set the ischecked parameter to your current state.


Html.CheckBox("IsActive", "Is Active", "true", ViewData.Model.IsActive)

No comments: