Reputation: 353
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?
Upvotes: 1
Views: 7839
Reputation: 53991
You'll notice in the Overload List that there's no overload for string, string, object
.
The overload you may be looking for is:
DropDownList(HtmlHelper, String, IEnumerable<SelectListItem>, Object)
You'd write this in your view as:
@Html.DropDownList("SomeString", MyEnumerable, new {@class = "required"}
The reason your second example works, i.e. string, null, object
is because IEnumerable<T>
is nullable.
UPDATE
You may find that DropDownListFor
is a better match for what you need.
The exact overload you'll probably want is:
HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, IEnumerable<SelectListItem>, Object
implimented as:
@Html.DropDownListFor(m => m.category_id, ViewBag.category_id, new {@class = "required"})
Upvotes: 2