开发者

Dropdownlist with IEnumerable Data type

开发者 https://www.devze.com 2023-03-19 19:00 出处:网络
My model looks like this public IEnumerable<SelectListItem> ProductTypes { get; set; } public ProductContent()

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);
    } 


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.


The root of the problem is that the types System.Web.WebPages.Html.SelectListItem and System.Web.Mvc.SelectListItem are not assignable.

It's likely that there are different namespace imports in the controller to the view. You need to be explicit in this case: either the model needs to use new System.Web.Mvc.SelectListItem(...) or the view needs to cast to (IEnumerable<System.Web.WebPages.Html.SelectListItem>).

0

精彩评论

暂无评论...
验证码 换一张
取 消