MVC3 DropDownList + ViewBag 问题 [英] MVC3 DropDownList + ViewBag issue
本文介绍了MVC3 DropDownList + ViewBag 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码工作正常
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");
在 HTML 下我有
under HTML I have
@Html.DropDownList("StateList", ViewBag.StateList)
无论如何我得到了错误
CS1973:System.Web.Mvc.HtmlHelper"没有名为DropDownList"的适用方法,但似乎具有该名称的扩展方法.不能动态调度扩展方法.考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法.
我该如何解决?
推荐答案
ViewBag
是一个 dynamic
对象,不能直接从您的视图中使用(这基本上就是错误所说的).你需要投射它:
The ViewBag
is a dynamic
object, which cannot be used directly from your View (that is basically what the error is saying). You'll need to cast it:
@Html.DropDownList("StateList", (SelectList) ViewBag.StateList)
另一种选择是使用 ViewData
,尽管它也可能需要强制转换.
Another option would be to use ViewData
though it may also require casting.
这篇关于MVC3 DropDownList + ViewBag 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文