Asp.net mvc 3 Can';t将htmlAttribute添加到Html.DropDownList

Asp.net mvc 3 Can';t将htmlAttribute添加到Html.DropDownList,asp.net-mvc-3,Asp.net Mvc 3,我需要使用jQuery对DropDownList进行一些验证。因此,我尝试添加一个htmlAttribute,如下所示: @Html.DropDownList("category_id", "Vælg..", new { @class = "required" }) 我收到以下错误: Error 2 'System.Web.Mvc.HtmlHelper<MvcApplication3.Models.Question>' does not contain a definiti

我需要使用jQuery对DropDownList进行一些验证。因此,我尝试添加一个
htmlAttribute
,如下所示:

@Html.DropDownList("category_id", "Vælg..", new { @class = "required" })
我收到以下错误:

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
它可以工作,但是没有默认值,这不是我想要的

我做错了什么?

您会在中注意到,
字符串、字符串、对象
没有重载

您可能要查找的过载是:

DropDownList(HtmlHelper, String, IEnumerable<SelectListItem>, Object)
第二个示例之所以有效,即
string、null、object
,是因为
IEnumerable
可以为null

更新

您可能会发现
DropDownListFor
更符合您的需要

您可能需要的确切过载是:

HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, IEnumerable<SelectListItem>, Object

我应该在HtmlHelper参数中写什么?您正在使用的@Html位已经涵盖了这一点。它与其他扩展方法相同,其中第一个参数被指定为(thishtmlhelper,…)。所以你可以忽略这个参数,知道它被@Html部分覆盖了。我正在从ViewBag中获取SelectList。它名为ViewBag.category_id-我已将代码更改为:@Html.DropDownList(“Kategorier”,ViewBag.category_id,new{@class=“required”}),但我收到了以下错误:错误1的System.Web.Mvc.HtmlHelper没有名为“DropDownList”的适用方法,但似乎有一个名为“DropDownList”的扩展方法。无法动态调度扩展方法。考虑在不使用扩展方法语法的情况下强制转换动态参数或调用扩展方法。C:\Heals\KeNAN\Deals\VisualStudio 2010 \项目\MVCpApple 3.3-拷贝\MVCpAptudio3\Value\Admin Qualth\GRIDQualth.CSHTML 38 38 MVcAptudio3什么是分类ID??如果是int,则字符串、int、object没有重载。这有意义吗?
@Html.DropDownList("SomeString", MyEnumerable, new {@class = "required"}
HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, IEnumerable<SelectListItem>, Object
@Html.DropDownListFor(m => m.category_id, ViewBag.category_id, new {@class = "required"})