Cannot convert type 'System.Web.Mvc.SelectList' to &
本文关键字:Mvc SelectList to Web System convert Cannot type | 更新日期: 2023-09-27 18:12:53
试图在我的视图中获得所有类别的列表,但它对我来说不是很好。这是我的控制器:
public ActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Products = _db.Products.ToList();
ViewBag.CategoryId = new SelectList(_db.Categories, "Id", "Name");
Product product = _db.Products.Find(id);
return View(product);
}
这是我试图在视图中运行的代码
var categories = ((List<string>) ViewBag.CategoryId);
但我确实得到了以下错误:
无法转换类型"System.Web.Mvc"。选择"System.Collections.Generic.List"
您需要在视图中将其转换为SelectList
,因为在控制器动作中您正在创建类型为SelectList
而不是List<string>
的对象:
var categories = ViewBag.CategoryId as SelectList;
为什么是SelectList
?你可以在你的动作方法中使用List:
ViewBag.Categories = _db.Categories.ToList();