我的模型是这样的
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.DbQuery
1[System.Web.WebPages.Html.SelectListItem]' to type 'System.Collections.Generic.IEnumerable
1[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/