Code Rider
Code Rider

Reputation: 2063

not able to bind a DropDownList in MVC

I'm new to MVC. I'm trying to bind a dropdownlist but facing an issue.

Following code of DataLayer:

public List<DataLayer.Customer> GetCustomers()
      {
          return obj.Customers.ToList();

      }

Controller Code:

 [Authorize]
         public ActionResult CreateOrder()
         {
             ViewBag.Message = "Crearte Order";
             ViewBag.Customers = manageOrder.GetCustomers();
             return View();
         }

View Code:

@Html.DropDownList("SelectedMovieType", (IEnumerable<SelectListItem>) ViewBag.Customers)

Getting following error when it try to bind the DropDownList

enable to cast object of type 'System.Collections.Generic.List1[DataLayer.Customer]' to type 'System.Collections.Generic.IEnumerable1[System.Web.Mvc.SelectListItem]'.

Let me know that how i can get ride of this issue.

Upvotes: 2

Views: 1027

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

ViewBag.Customers should be of type List<SelectListItem>.

Controller Code:

ViewBag.Customers = manageOrder.GetCustomers().Select(c => new SelectListItem { Text = c.TextProperty, Value = c.ValueProperty }).ToList();

View Code:

@Html.DropDownList("Customers")

Upvotes: 5

Related Questions