Dylan Czenski
Dylan Czenski

Reputation: 1365

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?

Upvotes: 5

Views: 13518

Answers (1)

Aman Sharma
Aman Sharma

Reputation: 1990

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"})

Upvotes: 6

Related Questions