asp.net-mvc – 如何在DropDownListFor的扩展中添加额外的html属性

我正在为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不会更改,但如果启用是真的我要添加@ disabled =“禁用”到html属性,然后再提供给AnonymousObjectToHtmlAttributes.

有什么想法呢?

解决方法

简单! HtmlHelper.AnonymousObjectToHtmlAttributes返回RouteValueDictionary.您可以向该字典添加值,您不需要向匿名对象添加属性.
public static MvcHtmlString DropDownListFor<TModel,bool enabled)
{
    var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    if (!enabled)
    {
        attrs.Add("disabled","disabled");
    }
    return htmlHelper.DropDownListFor(expression,attrs);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....