如何在DropDownListFor的扩展中添加额外的htmlattributes

时间:2012-03-08 20:05:39

标签: asp.net-mvc

我正在尝试为DropDownListFor编写扩展程序:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
    return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

我想要实现的是,如果启用为false则不更改但如果启用为true我想在将@disabled="disabled"添加到html属性之后再将其提供给AnonymousObjectToHtmlAttributes

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:33)

简单! HtmlHelper.AnonymousObjectToHtmlAttributes返回RouteValueDictionary。您可以为该字典添加值,您无需向匿名对象添加属性。

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
    var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    if (!enabled)
    {
        attrs.Add("disabled", "disabled");
    }
    return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, attrs);
}

答案 1 :(得分:2)

archil的解决方案。但是,对于你要做的事情,写一个扩展是一种矫枉过正。

只需在您的视图中写下:

@Html.DropDownListFor(m => m.Id, Model.Values, new { disabled = "disabled" })