How to set id and DropDownFor class - asp.net mvc

I am creating a small mvc app and using DropDownListFor in it. Iam was unable to set id and class for this dropdown. Below is my DropdownListFor code where I want to add Id and class. Timely help would be appreciated, thanks

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

      

+3


source to share


2 answers


@Html.DropDownListFor

In html helpers If you want to add any html attribute you must pass them as type objects htmlAttributes

as described by MSDN

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

      

Where htmlAttributes

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

      



So how does your question go

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

      

where keyword new

creates object for htmlattributes

+9


source


To install id

and class

of @Html.DropDownListFor

, use below code:

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

      



To set the html attributes inside @Html.DropDownListFor

you need to set the 4th @Html.DropDownListFor

keyword parameter new

which will create object

for htmlattributes

.

+2


source







All Articles