asp.net-mvc 将 DropdownlistFor 与 Viewbag 绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20563801/
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
Bind DropdownlistFor with the Viewbag
提问by Karan
I am trying to bind the DropDownListFor helper with the viewbag defined in the controller. But i am getting error.
我正在尝试将 DropDownListFor 助手与控制器中定义的视图包绑定。但我收到错误。
View Code:-
查看代码:-
@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem))
Controller Code:-
控制器代码:-
public ActionResult Create()
> {
> var content = from p in db.Currency
> where p.IsActive == true
> orderby p.CurrencyName
> select new { p.CurrencyID, p.CurrencyCode };
>
> var x = content.ToList().Select(c => new SelectListItem
> {
> Text = c.CurrencyCode,
> Value = c.CurrencyID.ToString(),
> Selected = (c.CurrencyID == 68)
> }).ToList();
> ViewBag.CurrencyList = x;
>
> return View();
> }
Error Received:- System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' has some invalid arguments
收到错误:- System.Web.Mvc.HtmlHelper' 不包含 'DropDownListFor' 的定义和最佳扩展方法重载 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System. Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' 有一些无效的参数
回答by Zabavsky
You need to change
你需要改变
@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem))
to
到
@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>)
回答by Uro? Goljat
You can also do this. It should work:
你也可以这样做。它应该工作:
ViewBag.CurrencyID = x;
and in view:
并认为:
@Html.DropDownListFor(model => model.CurrencyID, null)
Hope this helps!
希望这可以帮助!

