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:
- 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()); } } }
- 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> <h2>Category</h2> <ul> @foreach(var item in Model) { <li>@item.CategoryName</li> } </ul>
- Invoke the view component in the _Layout.cshtml page:
<div class="container"> <main role="main" class="pb-3"> @await Component.InvokeAsync("Category") @RenderBody() </main> </div>
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,
Dillion