Created
May 24, 2013 02:07
-
-
Save bruno-cadorette/5640838 to your computer and use it in GitHub Desktop.
MVC 3 checkbox list for
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
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Web; | |
| using System.Web.Mvc; | |
| using System.Linq.Expressions; | |
| public static class CheckBoxListForExtensions | |
| { | |
| public static MvcHtmlString CheckBoxListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, SelectList selectList) | |
| { | |
| ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); | |
| string htmlFieldName = ExpressionHelper.GetExpressionText(expression); | |
| string listHTML = "<ul>"; | |
| int[] selectedValues = (int[])selectList.SelectedValue; | |
| foreach (var selectListItem in selectList) | |
| { | |
| if (selectedValues != null && selectedValues.Contains(int.Parse(selectListItem.Value))) | |
| { | |
| selectListItem.Selected = true; | |
| } | |
| var id = selectListItem.Value + selectListItem.Text; | |
| listHTML += "<li>"; | |
| listHTML += String.Format("<input type='checkbox' name='{0}' value='{1}' {2} id='{3}' />" | |
| , new object[] { htmlFieldName, selectListItem.Value, (selectListItem.Selected == true ? "checked='checked'" : ""), id }); | |
| listHTML += String.Format("<label for='{0}'>{1}</label>", id, selectListItem.Text); | |
| listHTML += "</li>"; | |
| } | |
| listHTML += "</ul>"; | |
| return MvcHtmlString.Create(listHTML); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment