Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created April 8, 2013 07:56
Show Gist options
  • Save ChrisMcKee/5335024 to your computer and use it in GitHub Desktop.
Save ChrisMcKee/5335024 to your computer and use it in GitHub Desktop.
Checkbox Extension
namespace UI.Helpers
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class FormHtmlHelperExtensions
{
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty[]>> expression,
MultiSelectList multiSelectList,
object htmlAttributes = null, string prefix = "")
{
//Derive property name for checkbox name
MemberExpression body = expression.Body as MemberExpression;
string propertyName = body.Member.Name;
//Get currently select values from the ViewData model
TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
//Convert selected value list to a List<string> for easy manipulation
IList<string> selectedValues = new List<string>();
if (list != null)
{
selectedValues = new List<TProperty>(list).ConvertAll(delegate(TProperty i) { return i.ToString(); });
}
//Create div
TagBuilder divTag = new TagBuilder("div");
divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
divTag.InnerHtml += String.Format("<div class=\"group multi-select-options\">");
//Add checkboxes
foreach (SelectListItem item in multiSelectList)
{
var item2 = item;
var id = "multi-select-" + Guid.NewGuid().ToString();
divTag.InnerHtml +=
String.Format(
"<div class=\"group field multi-select-option\"><input type=\"checkbox\" name=\"{4}{0}\" id=\"{0}_{1}_{5}\" " +
"value=\"{1}\" {2} /><label for=\"{0}_{1}_{5}\">{3}</label></div>",
propertyName,
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
item.Text, prefix, id);
}
divTag.InnerHtml += String.Format("</div>");
return MvcHtmlString.Create(divTag.ToString());
}
}
}

Razor

@Html.CheckBoxListFor(model => model.SelectedSomethingIds, Model.Somethings, new { @class = "required" })

View Model

public MultiSelectList Somethings { get; set; } public int[] SelectedSomethingIds { get; set; }

Controller

// _listService.GetSomethings() returns IEnumerable

model.Somethings = new MultiSelectList(_listService.GetSomethings(), "Id", "Name");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment