2013-12-13 32 views
11

我想绑定DropDownListFor的助手与控制器中定义的viewbag。但我得到错误。绑定DropdownlistFor与Viewbag

查看代码: -

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem)) 

控制器代码: -

收到
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();    
>   } 

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

+0

你不能指定单个selectListItem到下拉列表。 ViewBag.CurrencyList作为SelectListItem,在这里您需要一个选择列表或列表或Enumerable项目。所以IEnumerable工作。只要你想知道。 – Sakthivel

回答

23

您需要更改

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem)) 

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>) 
+1

非常感谢。有用。 – Karan

5

您也可以这样做。它应该工作:

ViewBag.CurrencyID = x; 

,并考虑:

@Html.DropDownListFor(model => model.CurrencyID, null) 

希望这有助于!