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

时间:2014-09-26 07:15:07

标签: asp.net-mvc-4

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

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

2 个答案:

答案 0 :(得分:13)

@Html.DropDownListFor 在html帮助程序中如果要添加任何html属性,则必须将其作为htmlAttributes类型的对象传递,如MSDN解释< / p>

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

htmlAttributes在哪里

Type: System.Object
An object that contains the HTML attributes to set for the element

所以你的问题就是

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

其中new关键字为htmlattributes

创建一个对象

答案 1 :(得分:2)

要设置id的{​​{1}}和class,请使用以下代码:

@Html.DropDownListFor

要在@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" }) 中设置html属性,您必须使用@Html.DropDownListFor关键字设置@Html.DropDownListFor的第4个参数,这将为{{new创建object 1}}