无法将类型'System.Web.Mvc.SelectList'转换为'System.Collections.Generic.List <string>'

时间:2015-09-15 13:20:08

标签: c# asp.net-mvc

尝试在我的视图中获取所有类别的列表,但这对我来说效果不佳。 这是我的控制者:

var userIds = ["55f6c3639e3cdc00273b57a5", 
        "55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];

$scope.userList = [
    {id: "55f6c3639e3cdc00273b57a5", name: "ASD"},
    {id: "55f6c36e9e3cdc00273b57a6", name: "XYZ"}
  ];

$scope.filteredList = $filter('filter')( $scope.userList, function(user){
  return userIds.indexOf(user.id) != -1;
});

这是我尝试在我的视图中运行的代码

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

但我确实得到以下错误:

  

无法将'System.Web.Mvc.SelectList'类型转换为'System.Collections.Generic.List'

2 个答案:

答案 0 :(得分:1)

您需要在View中将其强制转换为SelectList,因为在控制器操作中您要创建SelectList类型的对象而不是List<string>

var categories = ViewBag.CategoryId as SelectList;

答案 1 :(得分:0)

为什么SelectList?您只需在操作方法中使用List:

ViewBag.Categories = _db.Categories.ToList();