Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind DropdownlistFor with the Viewbag

I am trying to bind the DropDownListFor helper with the viewbag defined in the controller. But i am getting error.

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

like image 806
Karan Avatar asked Dec 13 '13 10:12

Karan


People also ask

How do you bind a static value to a DropDownList in MVC?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


2 Answers

You need to change

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

to

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>)
like image 137
Zabavsky Avatar answered Oct 02 '22 18:10

Zabavsky


You can also do this. It should work:

ViewBag.CurrencyID = x;

and in view:

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

Hope this helps!

like image 20
Uroš Goljat Avatar answered Oct 02 '22 18:10

Uroš Goljat