razor - Nested foreach loop in ASP.NET MVC Core NullReferenceException -


i'm trying add navigation sidebar in simple web app has 2 primary models, , i'm running peculiar error when try use nested loop render data in sidebar.

my app has 2 models category , thing in example below:

public class category {     public int id { get; set; }     public string name { get; set; }     public virtual icollection<thing> things { get; set; } }  public class thing {     public int id { get; set; }     public string title { get; set; }     public string description { get; set; }     public int categoryid { get; set; }     public virtual category category { get; set; } } 

i want add sidebar contains list of categories. created viewcomponent i'm referencing in _layout.cshtml so:

// sidebarviewcomponent.cs public class sidebarviewcomponent : viewcomponent {     private readonly mycontext db;      public sidebarviewcomponent(mycontext context)     {         db = context;     }      public async task<iviewcomponentresult> invokeasync()     {         var categories = await getcategoriesasync();         return view(categories);     }      private task<list<category>> getcategoriesasync()     {         return db.category.tolistasync();     } }  // view file sidebarviewcomponent @model ienumerable<myapp.models.category> <div id="sidebar">     @foreach (var category in model)     {         <div class="header">@category.name</div>             @foreach (var thing in @category.things)             {                 <div>@thing.title</div>             }         </div>     } </div>  // _layout.cshtml <!doctype html> <html> <head>     <meta charset="utf-8" />     <title>@viewdata["title"]</title>      <!-- stylesheets -->     <link rel="stylesheet" href="~/css/site.css"> </head> <body>     @await component.invokeasync("sidebar")     @renderbody() </body> </html> 

when access page that's rendered thingcontroller, works perfectly. on home page or page handled categorycontroller, error "nullreferenceexception: object reference not set instance of object." @ line @foreach (var thing in @category.things).

how can sidebar work on every page?

okay, able working changing viewcomponent's getcategoriesasync method use eager loading of related collection:

private task<list<category>> getcategoriesasync() {     return db.category.include(c => c.things).tolistasync(); } 

this microsoft doc pointed me in right direction.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -