Snowing Code

Personal notes on software development

ASP.NET MVC CheckBoxList

(Publish date: 26/01/2010)

This is a very simple implementation of a check box list that we use rather frequently and which hasn’t let us down (yet).

First thing to do is to write a class inheriting from Dictionary<T, bool> for our multiple choice select list, something like the following:

public class CheckedList<T> : Dictionary<T, bool>

The idea is quite simply having a boolean value per each entity we want our users to be able to select. The dictionary also allows us not to worry about duplications…

then we add an HtmlHelper extension method:

public static class HtmlHelperExtensions
           public static string CheckBoxList<T, TModel, TValue, TText>(this HtmlHelper<TModel> helper, string listName, string valueProperty,
           string textProperty, CheckedList<T> checkedList, Func<T, TValue> value, Func<T, TText> text)
           StringBuilder builder = new StringBuilder();
           for (int i = 0; i < checkedList.Count; i++)
           T item = checkedList.Keys.ToList()[i];
           builder.AppendLine(helper.Hidden(listName + "[" + i + "].Key." + valueProperty, value(item)).ToHtmlString());
           builder.AppendLine(helper.Hidden(listName + "[" + i + "].Key." + textProperty, text(item)).ToHtmlString());
           builder.AppendLine(helper.CheckBox(listName + "[" + i + "].Value", checkedList[item]).ToHtmlString());
           return builder.ToString();

This extension method could be refactored so that it’ll take Expression<Func… , that way we could extract the names of the value and text properties.

What’s left now to do is simply call the extension method from our View like so:

<%= Html.CheckBoxList("MyCheckedList", "Id", "Name", Model.MyCheckedList, x=>x.Id, x=>x.Name) %> 

Needless to say, this is only a demo and serves just to show what a check box list can be achieved; for more features and more possibilities, you could implement your very own IDictionary<T, bool>, that way you could extend and add whatever you need.

noice :)


Seeing that the post seem to get quite a few hits and finds itself on the first page of a google search for the terms ‘mvc checkbox list’, I thought I should provide a sample project on github. Let me know if there are any problems.

Tags: mvc
blog comments powered by Disqus