C# MVC3 DropDownList + ViewBag 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9642821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC3 DropDownList + ViewBag issue
提问by Developer
This code works fine
这段代码工作正常
List<StateModelView> stateList = (from x in db.States
select new StateModelView {
ID = x.ID,
StateName = x.StateName
}).OrderBy(w => w.StateName).ToList();
ViewBag.StateList = new SelectList(stateList, "ID", "StateName");
under HTML I have
在 HTML 下我有
@Html.DropDownList("StateList", ViewBag.StateList)
Anyway I got the error
无论如何我得到了错误
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
CS1973:“System.Web.Mvc.HtmlHelper”没有名为“DropDownList”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法。
How I can resolve it?
我该如何解决?
采纳答案by M.Babcock
The ViewBagis a dynamicobject, which cannot be used directly from your View (that is basically what the error is saying). You'll need to cast it:
这ViewBag是一个dynamic对象,不能直接从您的视图中使用(这基本上就是错误所说的)。你需要投射它:
@Html.DropDownList("StateList", (SelectList) ViewBag.StateList)
Another option would be to use ViewDatathough it may also require casting.
另一种选择是使用,ViewData尽管它可能也需要铸造。
回答by akiller
You need to cast your ViewBag item (which is anonymous) to a SelectList:
您需要将 ViewBag 项目(匿名)转换为 SelectList:
@Html.DropDownList("StateList", (SelectList)ViewBag.StateList)
Another method to get around this casting issue and from what I gather the preferred way, is to use a View Model and bypass ViewBag all together.
解决这个投射问题的另一种方法以及我收集到的首选方法是使用视图模型并一起绕过 ViewBag。

