问题描述
我在做 webforms 多年后正在构建我的第一个 MVC 应用程序,但由于某种原因我无法完成这项工作:
I'm building my first MVC application after years of doing webforms, and for some reason I am not able to make this work:
@Html.DropDownList("PriorityID", String.Empty, new {@class="textbox"} )
错误信息:
System.Web.Mvc.HtmlHelper
' 不包含 DropDownList
的定义和最佳扩展方法重载 System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable, object)
有一些无效的参数
System.Web.Mvc.HtmlHelper<SPDR.Models.Bug>
' 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>, object)
has some invalid arguments
非常感谢任何帮助!
推荐答案
看着控制器,并更多地了解 MVC 的实际工作原理,我能够理解这一点.
Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.
我的视图是自动生成的视图之一,包含以下代码行:
My view was one of the auto-generated ones, and contained this line of code:
@Html.DropDownList("PriorityID", string.Empty)
要添加 html 属性,我需要做这样的事情:
To add html attributes, I needed to do something like this:
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })
再次感谢@Laurent 的帮助,我意识到问题并没有想象的那么清楚......
Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...
更新:
这样做的更好方法是使用 DropDownListFor 在可能的情况下,这样您就不会依赖于名称属性的魔法字符串
A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute
@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })
这篇关于添加 css 类以使用 @Html.DropDownList() 进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!