C# – Dropdownlist with IEnumerable Data type

asp.net-mvcasp.net-mvc-3cmodel-view-controller

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.DbQuery1[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);
    } 

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:

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.