My model looks like this
public IEnumerable<SelectListItem> ProductTypes { get; set; }
public ProductContent()
{
productxEntities db = new productxEntities();
ProductTypes = db.ProductCodes.Select(c => new SelectListItem
{
Value = c.product_type.ToString(),
Text = c.code.ToString()
});
}
when i try to use it for DropDownList
I get a error saying casting is wrong… what is the correct way of populating DDL using list from DB in MVC3 Razor C#, i have a tightly coupled view for this model type.
@Html.DropDownList("ProductTypes", (IEnumerable<SelectListItem>) Model.ProductTypes)
this is the error
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery
1[System.Web.WebPages.Html.SelectListItem]' to type 'System.Collections.Generic.IEnumerable
1[System.Web.Mvc.SelectListItem]'.
this is my controller
public ActionResult Create()
{
ProductContent productViewModel = new ProductContent();
return PartialView("../PartialViews/NewProduct", productViewModel);
}
Best Answer
You should be calling
ToList
somewhere in your EF query. Otherwise you are returning a Queryable directly to your View.Possibly like this:
As I mentioned in my comment though; I'd discourage this kind of code in a constructor of a Model. Someone else should be assigning it to the Model.
You should then be able to remove your cast in your View.