foo bar
foo bar

Reputation: 180

Cannot convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.List<string>'

Tryinging to get a list of all my categories in my view but it is not working out that great for me. This is my controller:

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

And this is the code I try to run in my view

var categories = ((List<string>) ViewBag.CategoryId);

But I do get this following error:

Cannot convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.List'

Upvotes: 0

Views: 7466

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You would need to cast it to SelectList in View, as in controller action you are creating object of type SelectList not List<string> :

var categories = ViewBag.CategoryId as SelectList;

Upvotes: 1

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

Why SelectList? You can simply use List in your action method:

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

Upvotes: 0

Related Questions