c# - 具有 IEnumerable 数据类型的下拉列表

标签 c# asp.net-mvc model-view-controller asp.net-mvc-3

我的模型是这样的

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



    }

当我尝试将它用于 DropDownList 时,我收到一条错误消息,指出转换错误...在 MVC3 Razor C# 中使用来自 DB 的列表填充 DDL 的正确方法是什么,我有一个紧密的此模型类型的耦合 View 。

@Html.DropDownList("ProductTypes", (IEnumerable<SelectListItem>) Model.ProductTypes)

这是错误

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]'.

这是我的 Controller

public ActionResult Create()
    {
        ProductContent productViewModel = new ProductContent();
        return PartialView("../PartialViews/NewProduct", productViewModel);
    } 

最佳答案

您应该在 EF 查询中的某处调用 ToList。否则,您将直接向您的 View 返回一个 Queryable。

可能是这样的:

public ProductContent()
{
    productxEntities db = new productxEntities();

    ProductTypes = db.ProductCodes.ToList().Select(c => new SelectListItem
    {
        Value = c.product_type.ToString(),
        Text = c.code.ToString()
    });
}

正如我在评论中提到的那样;我不鼓励在模型的构造函数中使用这种代码。其他人应该将其分配给模型。

然后您应该能够在您的 View 中删除您的类型转换。

关于c# - 具有 IEnumerable 数据类型的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644011/

相关文章:

c# - 使用 jquery 在 html 表中显示来自模型(字典)的数据

c# - 无需先加载即可读取 tiff 文件的尺寸和分辨率

asp.net - MVC + 表单 : Post error

c++ - 如何在 Qt 项目 View 中为单个单元格设置委托(delegate)?

c# - 如何将 List<string> 绑定(bind)到 DataGridView 控件?

C# LINQ 使用值列表按子列表过滤复杂对象列表

c# - Paypal 按钮管理器不接受小数金额

c# - 我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN

php - MVC - 一个模型应该与(一个)其他模型交互吗?或者 Controller 应该这样做?

java - Play Framework JPA : how to implement one-to-many relationship?