1

I am working on a relatively simple ASP.NET MVC application in C# in Visual Studio. In this situation I am trying to pass a list of objects into my view and then display their names, but I keep getting an error

Categories does not exist in the current context

Here is the controller:

public IActionResult Index()
{
    List <CheeseCategory> categories = context.Categories.ToList();
    return View(categories);
}

And here is the View:

@model CheeseMVC.Models.CheeseCategory

@if (categories != null)
{
    foreach(var category in categories)
    {
        <ul>@category</ul>
    }
}

I have done this before, and I can't figure out what is going wrong here, does anyone have any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dylan K
  • 13
  • 3
  • Use `@model IEnumerable` since you're passing a list collection to view. – Tetsuya Yamamoto Mar 21 '18 at 03:34
  • `@if (categories != null)` needs to be `@if (Model != null)`, but then as soon as you navigate to the page you will get [this exception](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ) –  Mar 21 '18 at 03:36
  • 1
    And its `foreach(var category in Model)` –  Mar 21 '18 at 03:36
  • Thank you! All of these combined fixed my issues. – Dylan K Mar 21 '18 at 04:07

1 Answers1

3

You passed in a List<CheeseCategory>, but in your Razor file, you said model would be just a CheeseCategory. The @model declaration needs to match what you're passing in.

Also, replace categories with Model in the if statement in the Razor file.

Tim
  • 2,089
  • 1
  • 12
  • 21