如何创建ASP.NET MVC一个CheckBoxListFor扩展方法?方法、NET、ASP、CheckBoxListFor

2023-09-02 01:27:32 作者:吊儿郎当小也

我知道有间的ASP.NET MVC HTML辅助扩展方法 ListBoxFor 扩展方法,但我始终认为,一个复选框列表更加人性化的比列表框。

I know there is a ListBoxFor extension method among the ASP.NET MVC Html helper extension methods, but I always thought that a checkbox list is more user-friendly than a list box.

有良好的旧的WebForms非常方便的CheckBoxList 控制,但显然这是出来的照片吧。

There was a very convenient CheckBoxList control in good old WebForms, but obviously that is out of the picture now.

现在的问题是,为什么没有办法在ASP.NET MVC中创建一个复选框列表?我该如何编写创建一个复选框列表,并以同样的方式表现 ListBoxFor 的行为?

The question is, why is there no way in ASP.NET MVC to create a check box list? How can I write my own extension method that creates a check box list and behaves in a similar way ListBoxFor behaves?

推荐答案

下面是一个强类型的HtmlHelper的CheckBoxListFor处理选定的项目在您的可视数据模型的数组。我选择不包装器Html.CheckBox或Html.CheckBoxFor方法,因为我不希望我的复选框列表中隐藏的假的字段。

Here is a strongly typed HtmlHelper for CheckBoxListFor that handles selected items as an array in your viewdata model. I chose not to wrapper the Html.CheckBox or Html.CheckBoxFor methods as I don't want the hidden "false" fields in my checkbox lists.

请随时来改善这一点,转贴: - )

Please feel free to improve on this and repost :-)

//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());
}