I am trying to formulate a work-around for the lack of a \"checkbox group\" in ASP.NET MVC. The typical way to implement this is to have check boxes of the same name, each
Behold the final solution:
public static class Helpers
{
public static string CheckboxGroup(this HtmlHelper htmlHelper, Expression> propertySelector, int value) where TProperty: IEnumerable
{
var groupName = GetPropertyName(propertySelector);
var modelValues = propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);
var svalue = value.ToString();
var builder = new TagBuilder("input");
builder.GenerateId(groupName);
builder.Attributes.Add("type", "checkbox");
builder.Attributes.Add("name", groupName);
builder.Attributes.Add("value", svalue);
var contextValues = HttpContext.Current.Request.Form.GetValues(groupName);
if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.Contains(value)))
{
builder.Attributes.Add("checked", null);
}
return builder.ToString(TagRenderMode.Normal);
}
private static string GetPropertyName(Expression> propertySelector)
{
var body = propertySelector.Body.ToString();
var firstIndex = body.IndexOf('.') + 1;
return body.Substring(firstIndex);
}
}
And in your view:
<%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "1")%>(iv),
<%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "2")%>(vi),
<%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "3")%>(vii),
<%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "4")%>(ix)