There doesn't appear to be an overload that supports this. I am currently using Overload 2
DropDownListFor(HtmlHelper, Expression>, IEnumerable, IDictionary)
Here is my call
@Html.DropDownListFor(m => m.BandLeaderId, Model.BandLeaderList, Model.BandLeaderId)
I want to add:
new { @class = "form-control" }
The 3rd overload and 6th overload will take this an object, but then they do NOT include this, IDictionary to set the default value.
Do I have to use javascript after the fact to set the styling?
Use this form instead:
@Html.DropDownListFor(m => m.BandLeaderId, Model.BandLeaderList, new { @class = "form-control" })
Since your control is bound to BandLeaderId
, as in m => m.BandLeaderId
, whatever value you set in the model is what this control will use.
I always forget this nuance about the DropDownListFor
until I try to use it in my own projects and then remember that it doesn't work the way the documentation might lead you to believe. Thanks Stephen!
Original answer below
The overload that you probably want is this one:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes
)
Note, however, that you want to supply your default value to the SelectList
. As in:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
Applying it to your situation:
@Html.DropDownListFor(m => m.BandLeaderId,
new SelectList(Model.BandLeaderList, "BandLeaderId", "BandLeaderName", Model.BandLeaderId),
new { @class = "form-control" })
My assumptions here are that your Model.BandLeaderList
contains an IEnumerable
with properties of BandLeaderId
and BandLeaderName
. Substitute Key
and Value
if BandLeaderList
is a Dictionary
object instead.