将 class 添加到 HTML.DropDownListFor

Adding a class to HTML.DropDownListFor

我正在尝试向以下代码行添加一个 class 赋值,

        @Html.DropDownListFor(model => model.Business, new SelectList(
              new List<Object>{
                   new { ... },
                   new { ... },
                   new { ... }
                },
              "value",
              "text",
              2))

本网站 (HTML.DropDownListFor class assignment) 给出的一个答案建议将其添加为重载方法,将 'object htmlAttributes' 作为最后一个参数。但是,我看不到这个参数作为一个选项,所以我有点困惑这是怎么可能的。

在我的示例中,我使用了所有可能的重载方法,并且有 none 用于 html 属性。

使用以下重载:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
IDictionary<string, Object> htmlAttributes
)

这里是MSDN docs of the overload

这样做:

@Html.DropDownListFor(model => model.Business, 
                      new SelectList(new List<Object>
                                 { 
                                  new { ... },
                                  new { ... },
                                  new { ... } 
                                }, 
                                "value", "text", 2),
                     new { @class ="YourClass"})

或以下重载也将起作用:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
IDictionary<string, Object> htmlAttributes
)

这样:

@Html.DropDownListFor(model => model.Business, 
                      new SelectList(new List<Object> 
                                        { 
                                         new { ... }, 
                                         new { ... },
                                        }, "value", "text", 2), 
                      null,new { @class ="YourClass"})

MSDN docs of the overload

四个中的DropDownListFor overloads have HTML Attributes as their last parameter. This one可能是最简单的了。修改你的例子,它变成:

@Html.DropDownListFor(model => model.Business, 
                      new SelectList(
                          new List<Object>{
                              new { ... },
                              new { ... },
                              new { ... }
                          },
                          "value",
                          "text",
                          2),
                      new {
                          @class = "myclass"
                      })