public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, IEnumerable<TProperty>>> expression,
IEnumerable<SelectListItem> multiSelectList,
Object htmlAttributes = null)
{
// Derive property name for checkbox name
var body = expression.Body as MemberExpression;
if (body == null)
return null;
String propertyName = body.Member.Name;
// Get currently select values from the ViewData model
IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
// Convert selected value list to a List<String> for easy manipulation
var selectedValues = new List<String>();
if (list != null)
selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());
// Create div
var ulTag = new TagBuilder("ul");
ulTag.AddCssClass("checkBoxList");
ulTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
// Add checkboxes
foreach (var item in multiSelectList)
{
ulTag.InnerHtml += String.Format(
"<li><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></li>",
propertyName,
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
item.Text);
}
return MvcHtmlString.Create(ulTag.ToString());
}
Nhận xét
Đăng nhận xét