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.IEnumerable1[System.Web.Mvc.SelectListItem]'.
this is my controller
public ActionResult Create()
{
ProductContent productViewModel = new ProductContent();
return PartialView("../PartialViews/NewProduct", productViewModel);
}
You should be calling ToList somewhere in your EF query. Otherwise you are returning a Queryable directly to your View.
Possibly like this:
public ProductContent()
{
productxEntities db = new productxEntities();
ProductTypes = db.ProductCodes.ToList().Select(c => new SelectListItem
{
Value = c.product_type.ToString(),
Text = c.code.ToString()
});
}
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.
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