如何在ASP.NET MVC中创建CheckBoxListFor扩展方法?

Ven*_*emo 15 .net asp.net asp.net-mvc checkboxlist

我知道ListBoxForASP.NET MVC Html助手扩展方法中有一个扩展方法,但我一直认为复选框列表比列表框更加用户友好.

CheckBoxList在旧的WebForms中有一个非常方便的控制,但显然现在已经不在了.

问题是,为什么ASP.NET MVC中没有办法创建复选框列表?如何编写自己的扩展方法来创建复选框列表并以类似的方式运行ListBoxFor

Rob*_*Rob 33

这是一个用于CheckBoxListFor的强类型HtmlHelper,它将所选项目作为数组在viewdata模型中处理.我选择不包装Html.CheckBox或Html.CheckBoxFor方法,因为我不想在我的复选框列表中隐藏"false"字段.

请随意改进并重新发布:-)

//View

<%: Html.CheckBoxListFor(model => model.FreightTypeIds, FreightTypeMultiSelectList)  %>

//Controller

    public ActionResult SomeAction(int[] FreightTypeIds)
    {
       //...

       return View();
    }


//Extension
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TProperty>>> expression, MultiSelectList allOptions, object htmlAttributes = null)
{
    ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, IEnumerable<TProperty>>(expression, htmlHelper.ViewData);

    // Derive property name for checkbox name
    string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(modelMetadata.PropertyName);

    // 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
    IList<string> selectedValues = new List<string>();

    if (list != null)
    {
        selectedValues = new List<TProperty>(list).ConvertAll<string>(delegate(TProperty i) { return i.ToString(); });
    }

    // Create div
    TagBuilder divTag = new TagBuilder("div");
    divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

    // Add checkboxes
    foreach (SelectListItem item in allOptions)
    {
        divTag.InnerHtml += string.Format(
                                          "<div><input type=\"checkbox\" name=\"{0}\" id=\"{1}_{2}\" " +
                                          "value=\"{2}\" {3} /><label for=\"{1}_{2}\">{4}</label></div>",
                                          propertyName,
                                          TagBuilder.CreateSanitizedId(propertyName),
                                          item.Value,
                                          selectedValues.Contains(item.Value) ? "checked=\"checked\"" : string.Empty,
                                          item.Text);
    }

     return MvcHtmlString.Create(divTag.ToString());
}
Run Code Online (Sandbox Code Playgroud)