I need to use jQuery to do some validation on a DropDownList. Therefore I am trying to add a htmlAttribute like this:
@Html.DropDownList("category_id", "Vælg..", new { @class = "required" })
I am getting the following errors:
Error 2 'System.Web.Mvc.HtmlHelper<MvcApplication3.Models.Question>' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, string)' has some invalid arguments c:\Users\Kenan\Documents\Visual Studio 2010\Projects\MvcApplication3 - Copy\MvcApplication3\Views\AdminQuestion\GridQuestion.cshtml 38 14 MvcApplication3
Error 3 Argument 3: cannot convert from 'string' to 'System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>' c:\Users\Kenan\Documents\Visual Studio 2010\Projects\MvcApplication3 - Copy\MvcApplication3\Views\AdminQuestion\GridQuestion.cshtml 38 47 MvcApplication3
Error 4 Argument 4: cannot convert from 'AnonymousType#1' to 'string' c:\Users\Kenan\Documents\Visual Studio 2010\Projects\MvcApplication3 - Copy\MvcApplication3\Views\AdminQuestion\GridQuestion.cshtml 38 57 MvcApplication3
If I change the code to:
@Html.DropDownList("category_id", null, new { @class = "required " })
It works, but without a default value, which is not what I want.
What am I doing wrong?
You’ll notice in the Overload List that there’s no overload for
string, string, object.The overload you may be looking for is:
You’d write this in your view as:
The reason your second example works, i.e.
string, null, objectis becauseIEnumerable<T>is nullable.UPDATE
You may find that
DropDownListForis a better match for what you need.The exact overload you’ll probably want is:
implimented as: