Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating a small mvc applicaiton and using DropDownListFor in it. Iam unable to set an id and class for that dropdownlist. Following is my DropdownListFor code in which i want to add Id and class. Timely help will be appreciated, thanks

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--")
like image 315
user3004110 Avatar asked Sep 26 '14 07:09

user3004110


2 Answers

In order to set 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" })

In order to set html attributes inside @Html.DropDownListFor, you have to set 4th parameter of @Html.DropDownListFor with new keyword which will create a object for htmlattributes.

like image 194
Kartikeya Khosla Avatar answered Nov 10 '22 21:11

Kartikeya Khosla


@Html.DropDownListFor In html helpers If you want to add any html attribute you have to pass them as objects of htmlAttributes type , Like explained by MSDN

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

Where htmlAttributes are

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

So as your question goes

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

where new keyword creates an object for htmlattributes

like image 42
Tushar Avatar answered Nov 10 '22 19:11

Tushar