Last active
December 28, 2015 17:59
-
-
Save jarrettmeyer/7539291 to your computer and use it in GitHub Desktop.
An HTML Helper for creating an array of checkboxes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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