Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Last active December 28, 2015 17:59
Show Gist options
  • Select an option

  • Save jarrettmeyer/7539291 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/7539291 to your computer and use it in GitHub Desktop.
An HTML Helper for creating an array of checkboxes.
public static class HtmlHelpers
{
public static IHtmlString ArrayCheckBoxFor<TModel, TArray>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TArray[]>> expression, TArray value)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var tagBuilder = new TagBuilder("input");
tagBuilder.Attributes.Add("type", "checkbox");
tagBuilder.Attributes.Add("name", metadata.PropertyName);
tagBuilder.Attributes.Add("value", value.ToString());
TArray[] propertyValue = metadata.Model as TArray[];
bool isContainedInArray = propertyValue != null && propertyValue.Contains(value);
if (isContainedInArray)
tagBuilder.Attributes.Add("checked", "checked");
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
}
}
public class MyModel
{
// This must be an array. It can be an array of IDs if the
// list of possible values is pulled from a database.
public string[] Flowers { get; set; }
}
<label>
<input type="checkbox" name="Flowers" value="Lilacs" checked="checked"/> Lilacs
</label>
<label>
<input type="checkbox" name="Flowers" value="Marigolds"/> Marigolds
</label>
<label>
<input type="checkbox" name="Flowers" value="Roses" checked="checked"/> Roses
</label>
@model MyModel
<label>
@Html.ArrayCheckBoxFor(x => x.Flowers, "Lilacs") Lilacs
</label>
<label>
@Html.ArrayCheckBoxFor(x => x.Flowers, "Marigolds") Marigolds
</label>
<label>
@Html.ArrayCheckBoxFor(x => x.Flowers, "Roses") Roses
</label>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment