2013-12-13 102 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) 

希望這有助於!