asp.net mvc 3 - Can't add htmlAttribute to Html.DropDownList -


i need use jquery validation on dropdownlist. therefore trying add htmlattribute this:

@html.dropdownlist("category_id", "vælg..", new { @class = "required" }) 

i getting following errors:

error   2   'system.web.mvc.htmlhelper<mvcapplication3.models.question>' not contain definition 'dropdownlist' , 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 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 'string' '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 'anonymoustype#1' 'string'   c:\users\kenan\documents\visual studio 2010\projects\mvcapplication3 - copy\mvcapplication3\views\adminquestion\gridquestion.cshtml 38  57  mvcapplication3 

if change code to:

@html.dropdownlist("category_id", null, new { @class = "required " }) 

it works, without default value, not want.

what doing wrong?

you'll notice in overload list there's no overload string, string, object.

the overload may looking is:

dropdownlist(htmlhelper, string, ienumerable<selectlistitem>, object) 

you'd write in view as:

@html.dropdownlist("somestring", myenumerable, new {@class = "required"} 

the reason second example works, i.e. string, null, object because ienumerable<t> nullable.

update

you may find dropdownlistfor better match need.

the exact overload you'll 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"}) 

Comments