2013-12-13 10 views
11

私はDropDownListForヘルパをコントローラーで定義されたビューバックとバインドしようとしています。しかし、私はエラーが発生しています。バインドDropDownListFor with the 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'の定義と最適な拡張メソッドoverload 'System.Web.M vc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper、System.Linq.Expressions.Expression>、System.Collections.Generic.IEnumerable) 'に無効な引数がいくつかあります。

+0

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

を変更する必要があります。 ViewBag.CurrencyListはSelectListItemとして、ここでは選択リスト、リスト、またはEnumerableアイテムが必要です。だからIEnumerableが働いた。ちょうどあなたが知りたいと思った場合。 – Sakthivel

答えて

23

あなたがDropDownListコントロールするための単一のselectListItemを割り当てることはできません

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

ありがとうございました。できます。 – Karan

5

これも可能です。それは動作するはずです:

ViewBag.CurrencyID = x; 

やビューのを:

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

は、この情報がお役に立てば幸い!

関連する問題