Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign ID to Html.DropDownListFor

I have a dropdown list for a model property called SomProperty:

@Html.DropDownListFor(model => model.SomeProperty,(SelectList)ViewBag.items)

where in the controller, ViewBag.items is an IEnumerable<SelectListItem>.

How do I assign an ID to the dropdown list?

like image 926
Dylan Czenski Avatar asked Apr 28 '16 20:04

Dylan Czenski


People also ask

How to add Drop Down list in ASP net MVC 5?

"Start", then "All Programs" and select "Microsoft Visual Studio 2015". "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. Choose MVC empty application option and click OK.


1 Answers

Your usage is already correct. The ID will be SomeProperty. It will also contain the value of the item which end user selects.

@Html.DropDownListFor(model => model.SomeProperty, (SelectList)ViewBag.items, "-- Select --")

Still if you want to change the default ID name then you can do so as shown below (also describe by Stephen in comment)

@Html.DropDownListFor(model => model.SomeProperty, (SelectList)ViewBag.items, "-- Select --", new { id = "NewID"  })

Bonus: Optionally you can also specify css class for your drop down as:

@Html.DropDownListFor(model => model.SomeProperty, (SelectList)ViewBag.items, "-- Select --", new {@class = "form-control"})
like image 151
Aman Sharma Avatar answered Nov 07 '22 18:11

Aman Sharma