![](/img/trans.png)
[英]How to pass value from partial view to shared view _Layout.cshtml in asp.net MVC?
[英]How do you add data from the database to the shared _Layout.cshtml in ASP.NET Core MVC (.NET 6) application?
NET 大師們,我快要瘋了。 我已經嘗試了 3 天,但似乎沒有任何效果。 我創建了一個局部視圖,一個 base controller,嘗試了不同的功能。 我找到的每個解決方案都已過時。
有誰知道現在在 ASP.NET Core .NET 6, MVC with Razor pages 中怎么做? 我找不到合適的文檔。
我的 _Layout.cshtml 中有一個菜單,想在那里顯示數據庫中的類別,但 model 始終為 NULL。我在不同視圖中顯示數據沒有問題,我似乎無法將 model 添加到 _Layout .cshtml。
您可以嘗試使用視圖組件來呈現類別。
例如,我們可以參考以下步驟在MVC應用程序布局頁面中顯示類別:
創建名為 ViewComponents 的新文件夾。 在此文件夾中,創建名為 CategoryViewComponent.cs 的新 class,如下所示:
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()); } } }
在 Views 文件夾中,創建路徑為 Views\Shared\Components\Category 的新文件夾。 在類別文件夾中,創建名為 Index.cshtml 的新文件夾:
@model List<WebApplication1.Data.Category> <h2>Category</h2> <ul> @foreach(var item in Model) { <li>@item.CategoryName</li> } </ul>
在_Layout.cshtml頁面中調用視圖組件:
<div class="container"> <main role="main" class="pb-3"> @await Component.InvokeAsync("Category") @RenderBody() </main> </div>
文件結構如下:
然后,結果是這樣的:
如果使用 Razor 頁面應用程序,使用相同的代碼和文件結構如下:
然后,結果是這樣的:
更多詳細信息,您還可以參考Razor Pages 中的 View Components 。
布局視圖可以具有類型化的 model。對於 razor 頁,我將介紹一個基頁 model;
interface IViewTemplate{
IEnumerable<string> GetCategories();
}
public abstract class BasePageModel : PageModel, IViewTemplate{
...
}
public class MyPageModel : BasePageModel
...
}
那么你的觀點可以;
@model IViewTemplate
@foreach(var category in Model.GetCategories()){
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.