简体   繁体   中英

Using _ViewStart to render partial razor pages

I have an asp.net core project with the layout page:

_Layout.cshtml

Which is the default asp.net core _Layout page. No model involved.

In the Areas folder I have a couple of files:

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

These files look like this:

_ViewStart

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

_Menu

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

Index

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

<h1>Hello, world!</h1>

Now I want to visit the Vendor index Razor page, but I want it to also render the _Menu options first, hence the _ViewStart with the _Layout and also the _Menu - basically every Vendor page I visit should have the _Menu rendered first.

But when I visit Index I get this error:

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'

How can this be? I'm not passing anything to the Index page? And when I tried to specify null as an argument on RenderPartialAsync() I just get null reference exception on my _Menu page.

How can I achieve what I need?

It should render _Layout > _ViewStart > _Menu > AnyOtherVendorPage

Here is a working demo like below:

1.Partial view should be razor view instead of razor pages:

@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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM