How do you add data from the database to the shared _Layout.cshtml in ASP.NET Core MVC (.NET 6) application?

tma9 1 Reputation point

Hello, I have created a partial view, a base controller, tried out different functions. Every solution I have found is outdated.
Does anyone know how to do it now in ASP.NET Core .NET 6, MVC with Razor pages? I can't find the right documentation.
I have a menu in my _Layout.cshtml and want to display categories from database there, but the model is always NULL. I have no problem displaying the data in a different view, I just can't seem to add the model to the _Layout.cshtml.

A set of technologies in the .NET Framework for building web applications and XML web services.
2,826 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 21,706 Reputation points Microsoft Vendor

    Hi @tma9 ,

    How do you add data from the database to the shared _Layout.cshtml in ASP.NET Core MVC (.NET 6) application?

    You can try to use a View Component to render the category.

    For example, we could refer to the following steps to display category in the MVC application layout page:

    1. Create new folder named ViewComponents. In this folder, create new class named CategoryViewComponent.cs as below:
      using Microsoft.AspNetCore.Mvc;  
      using WebApplication1.Data;  
      namespace WebApplication1.ViewComponents  
          [ViewComponent(Name ="Category")]  
          public class CategoryViewComponent:ViewComponent  
              private readonly ApplicationDbContext _context;  
              public CategoryViewComponent(ApplicationDbContext applicationDbContext)  
                  _context = applicationDbContext;  
              public async Task<IViewComponentResult> InvokeAsync()  
                  return View("Index", _context.Categories.ToList());  
    2. In Views folder, create new folders with path Views\Shared\Components\Category. In Category folder, create new folder named Index.cshtml:
      @model List<WebApplication1.Data.Category>  
          @foreach(var item in Model)  
    3. Invoke the view component in the _Layout.cshtml page:
      <div class="container">  
          <main role="main" class="pb-3">  
              @await Component.InvokeAsync("Category")  

    The file structure as below:


    Then, the result is like this:


    In Razor page application, use the same code and the file structure as below:


    Then, the result is like this:


    More detail information, you can also refer View Components in Razor Pages.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    1 person found this answer helpful.