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

Ano*_*use 11 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));
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是如果启用是假的没有改变但是如果启用是真我想@disabled="disabled"在给它们之前添加到html属性AnonymousObjectToHtmlAttributes.

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

arc*_*hil 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要编写帮助程序,只需使用接受htmlAttributes的重载,如Dmitry建议的那样. (3认同)
  • @ Rick.Anderson-at-Microsoft.com我不同意.首先,问题是添加属性,而不是使用其他方法的可能性.其次,在这种情况下创建帮助程序比检查启用条件然后从视图调用正确的方法重载更具可读性 (2认同)