使用Viewbag绑定DropdownlistFor

Kar*_*ran 11 asp.net-mvc asp.net-mvc-4

我试图将DropDownListFor帮助器与控制器中定义的viewbag绑定.但我收到了错误.

查看代码: -

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem)) 
Run Code Online (Sandbox Code Playgroud)

控制器代码: -

 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();            
>         }
Run Code Online (Sandbox Code Playgroud)

收到错误: - System.Web.Mvc.HtmlHelper'不包含'DropDownListFor'的定义和最佳扩展方法重载'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,System. Linq.Expressions.Expression>,System.Collections.Generic.IEnumerable)'有一些无效的参数

Zab*_*sky 24

你需要改变

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem))
Run Code Online (Sandbox Code Playgroud)

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>)
Run Code Online (Sandbox Code Playgroud)


Uro*_*jat 5

你也可以这样做.它应该工作:

ViewBag.CurrencyID = x;
Run Code Online (Sandbox Code Playgroud)

在视野中:

@Html.DropDownListFor(model => model.CurrencyID, null)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!