[英]Using _ViewStart to render partial razor pages
I have an asp.net core project with the layout page:我有一个带有布局页面的 asp.net 核心项目:
_Layout.cshtml
Which is the default asp.net core _Layout page.这是默认的asp.net core_Layout页面。 No model involved.
不涉及 model。
In the Areas
folder I have a couple of files:在
Areas
文件夹中,我有几个文件:
Vendor > Pages > _ViewStart.cshtml
Vendor > Pages > _Menu.cshtml
Vendor > Pages > Index.cshtml
These files look like this:这些文件如下所示:
_ViewStart _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.现在我想访问
Vendor
索引 Razor 页面,但我希望它也首先呈现_Menu
选项,因此带有_ViewStart
和_Layout
的_Menu
- 基本上我访问的每个供应商页面都应该首先呈现_Menu
。
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?我没有向
Index
页面传递任何内容? And when I tried to specify null
as an argument on RenderPartialAsync()
I just get null reference exception
on my _Menu page.当我尝试将
null
指定为RenderPartialAsync()
上的参数时,我只是在我的 _Menu 页面上得到null reference exception
。
How can I achieve what I need?我怎样才能达到我所需要的?
It should render _Layout > _ViewStart > _Menu > AnyOtherVendorPage它应该呈现 _Layout > _ViewStart > _Menu > AnyOtherVendorPage
Here is a working demo like below:这是一个工作演示,如下所示:
1.Partial view should be razor view instead of razor pages: 1.部分视图应该是razor视图而不是razor页面:
@model List<YourProject.Models.MenuItem>
@{
foreach (var i in Model)
{
@Html.ActionLink(i.DisplayText, i.Url)
}
}
2._ViewStart.cshtml: 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.