问题
Is it possible to assign my own class to the HTML.DropDownListFor() helper?
回答1:
One of the overloaded method has an object htmlAttributes
as last parameter in which you can specify extra attributes to be added to the generated html:
Html.DropDownListFor(..., new { "class" = "myclassname" };
http://msdn.microsoft.com/library/ee703670.aspx
回答2:
Didier's answer is mostly correct, but to define a class value in htmlAttributes object, you need to use this syntax:
Html.DropDownListFor(..., new { @class = "myclassname" } );
The "@" is to let the compiler know that this is not the keyword "class". Using "class"
will result in a compilation error.
回答3:
You can use any of the below logic.
@Html.DropDownList("CourseId", new List<SelectListItem>(), new {@class="myclassname"} )
OR
@Html.DropDownList("CourseId", (IEnumerable<SelectListItem>)ViewBag.CourseId, new { @class="myclassname" })
OR
@Html.DropDownListFor(x => x.CourseId, (IEnumerable<SelectListItem>)ViewBag.CourseId, new { @class = "myclassname" })
来源:https://stackoverflow.com/questions/7970701/html-dropdownlistfor-class-assignment