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
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.
You need to change
@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem))
to
@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>)
You can also do this. It should work:
ViewBag.CurrencyID = x;
and in view:
@Html.DropDownListFor(model => model.CurrencyID, null)
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With