如何设置DropDownFor的id和类 - asp.net mvc

use*_*110 5 asp.net-mvc-4

我正在创建一个小的mvc应用程序并在其中使用DropDownListFor.我无法为该下拉列表设置id和类.以下是我想要添加Id和类的DropdownListFor代码.及时的帮助将不胜感激,谢谢

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--")
Run Code Online (Sandbox Code Playgroud)

Tus*_*har 17

@Html.DropDownListFor在html助手中如果你想添加任何html属性,你必须将它们作为htmlAttributes类型的对象传递,如MSDN所解释的那样

public static MvcHtmlString DropDownListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    IEnumerable<SelectListItem> selectList,
    Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

htmlAttributes的位置

Type: System.Object
An object that contains the HTML attributes to set for the element
Run Code Online (Sandbox Code Playgroud)

所以你的问题就是这样

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })
Run Code Online (Sandbox Code Playgroud)

其中newkeyword为htmlattributes创建一个对象


Kar*_*sla 5

为了设置idclass使用@Html.DropDownListFor以下代码:

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })
Run Code Online (Sandbox Code Playgroud)

为了在内部设置 html 属性@Html.DropDownListFor,您必须设置@Html.DropDownListForwithnew关键字的第四个参数,这将创建一个objectfor htmlattributes