簡體   English   中英

使用 _ViewStart 渲染部分 razor 頁面

[英]Using _ViewStart to render partial razor pages

我有一個帶有布局頁面的 asp.net 核心項目:

_Layout.cshtml

這是默認的asp.net core_Layout頁面。 不涉及 model。

Areas文件夾中,我有幾個文件:

Vendor > Pages > _ViewStart.cshtml
Vendor > Pages > _Menu.cshtml
Vendor > Pages > Index.cshtml

這些文件如下所示:

_ViewStart

@{
    Layout = "/Views/Shared/_Layout.cshtml";
}
@{ await Html.RenderPartialAsync("_Menu"); }

_菜單

@page
@model MyProject.Areas.Vendor.Pages.MenuModel
@{
    foreach(var i in Model.MenuItems)
    {
        @Html.ActionLink(i.DisplayText,i.Url)
    }
}

指數

@page
@model MyProject.Areas.Vendor.Pages.IndexModel
@{
}

<h1>Hello, world!</h1>

現在我想訪問Vendor索引 Razor 頁面,但我希望它也首先呈現_Menu選項,因此帶有_ViewStart_Layout_Menu - 基本上我訪問的每個供應商頁面都應該首先呈現_Menu

但是當我訪問索引時,我得到了這個錯誤:

The model item passed into the ViewDataDictionary is of type 'MyProject.Areas.Vendor.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'MyProject.Areas.Vendor.Pages.MenuModel'

怎么會這樣? 我沒有向Index頁面傳遞任何內容? 當我嘗試將null指定為RenderPartialAsync()上的參數時,我只是在我的 _Menu 頁面上得到null reference exception

我怎樣才能達到我所需要的?

它應該呈現 _Layout > _ViewStart > _Menu > AnyOtherVendorPage

這是一個工作演示,如下所示:

1.部分視圖應該是razor視圖而不是razor頁面:

@model List<YourProject.Models.MenuItem>
@{
    foreach (var i in Model)
    {
        @Html.ActionLink(i.DisplayText, i.Url)
    }
}

2._ViewStart.cshtml:

@{
    Layout = "/Views/Shared/_Layout.cshtml";
    var model = new List<YourProject.Models.MenuItem>()
    {
        new YourProject.Models.MenuItem(){ DisplayText="aaa", Url="aaa" },
        new YourProject.Models.MenuItem(){ DisplayText="bbb", Url="bbb" },
    };
}

@{ await Html.RenderPartialAsync("_Menu", model); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM