CheckBoxList Helper extension method ASP.NET MVC 3

Here’s a quick and dirty html helper for checkboxes in ASP.NET MVC 3. I’m sure Microsoft will eventually package one with the MVC framework just like they will a radiobuttonlist helper, but in the meantime, this one suits my purposes.

Of course, from a front-end point of view, a multi-select listbox is also an option, but checkboxes are a little more robust when it comes to user interaction. Nothing is more annoying as a user than forgetting to ctrl-click and having all your previous selections disappear.

You can probably find variations around, most that I’ve seen use a generic list of a custom class – mine uses a MultiSelectList instead, just for fun.

public static class NSCheckboxListExtensions
    {
        public static MvcHtmlString CheckboxListFor<TModel, TProperty>(
                    this HtmlHelper<TModel> htmlHelper,
                    Expression<Func<TModel, TProperty>> expression,
                    MultiSelectList listOfValues)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var sb = new StringBuilder();

            if (listOfValues != null)
            {
                foreach (var item in listOfValues)
                {
                    var id = string.Format("{0}_{1}", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)), item.Value);
                    var name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));

                    var cb = new TagBuilder("input");
                    cb.MergeAttribute("type", "checkbox");
                    cb.MergeAttribute("name", name);
                    cb.MergeAttribute("value", @item.Value);
                    cb.MergeAttribute("id", id);
                    if (@item.Selected)
                    {
                        cb.MergeAttribute("checked", "checked");
                    }
                    sb.AppendFormat("{0}{1}</br>", cb, label);
                }
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }