HTML helper DropDownList explained

asp.net, asp.net-mvc

Solution

You're calling this overload. This creates a dropdown list with the name "FinancialYearID" (which means that the selected value will bind to a model or ViewBag property called "FinancialYearID") and "Select FY" as the placeholder (empty) selection text.

If you want to add a class, you need the `DropDown(string, IEnumerable, string, object)` helper:

@Html.DropDownList("FinancialYearID", null, "Select FY", new { @class = "foo" })

Here, you can also populate the DropDownList by passing in an `IEnumerable` (such as a `SelectList`) where I have passed `null`.

Yes, it is entirely possible to pass a data attribute. just replace the hyphen with an underscore:

@Html.DropDownListFor("FinancialYearID", null,
                   "Select FY", new { @data_something = "foo" })

If you have a model property to which you're trying to bind the selected value, you can pass a lamba expression to indicate the property that you want to bind and the framework will generate the appropriate `name`:

@Html.DropDownList(m => m.FinancialYearID, MySelectList,
                   "Select FY", new { @data_something = "foo" })

I'd also generally advise putting the `SelectList` in the model on the initial GET request rather than using `ViewBag`.

Problem

Can someone please explain how this works? (which overload is being used) ``` @Html.DropDownList("FinancialYearID", "Select FY") ``` FinancialYearID is a SelectList in view bag. Why is it passed as a string? Also how can I add custom attributes on the input element? Adding a 3rd parameter ``` new { @class = "foo" } ``` doesn't work? Is it possible to add data- attributes using the default helpers? Thanks

Original source