Asp – MVC DropDownList parameter problem

asp.net-mvc

The following dropdown does exactly what I want, but I'm looking for a simpler way to express it (note this is VB syntax).

<%=Html.DropDownList("values", CType(ViewData("values"), IEnumerable(Of SelectListItem)), "No values", New With {.onchange = "this.form.submit();"})%>

Because the ViewData value is named the same as the dropdown, the HTML helper lets the following work:

<%=Html.DropDownList("values", "No values")%>

but as soon as I try to add the onchange code:

<%=Html.DropDownList("values", "No values", New With {.onchange = "this.form.submit();"})%>

I get the "Overload resolution failed because no accessible "DropDownList" can be called without a narrowing conversion" error.

How can I take advantage of the HTML helper functionality but still specify htmlAttributes?

Best Answer

EDIT

Looking at the source code online it appears that, unlike most of the other HtmlHelper extensions, the Select extensions don't check for null in the values and default to loading based on the model/viewdata. If you don't want to write your own extension, it appears the best way is to cast the view data as you are doing in your first sample. After checking my own code I find that that is, in fact, what I do.

Original answer left for context:

Simply specify the select list as Nothing and it will pull it from your model/viewdata as you expect it. This allows the compiler to match an existing method signature, but doesn't require that you tell it exactly the list to use. If you look at the source code (www.codeplex.com/aspnet), you'll see that the methods with fewer parameters do just this sort of substitution, calling the methods with more parameters with suitable defaults.

<%=Html.DropDownList("values",
                     Nothing,
                     "No values",
                     New With {.onchange = "this.form.submit();"})%>