假设在我的文件夹Dashboard
我有一个名为PartialView
的_RightSidebar
,我需要在_PartialView
中包含这个DashBoard
,所以我正在寻找一种方法来加载_RightSidebar
只有当用户在Dashboard
的视图内。
实际上我加载_RightSidebar
_Layout
但如果我不在Dashboard
我会得到一个错误,因为_RightSidebar
只是Dashboard
的一部分(我想避免为每个仪表板视图创建冗余代码)。
Section
已经存在相同的机制,但我找不到类似于_PartialView
的任何东西,有人知道如何做到这一点?
在您的布局中,只需定义一个可选部分,然后在仪表板页面上,渲染此部分中的局部视图:
Layout.cshtml:
@RenderSection("RightSidebar", false);
@RenderBody()
Dashboard.cshtml
@page
@section RightSidebar {
@await Html.PartialAsync("_RightSidebar.cshtml")
}
//编辑:使用布局继承替代回答。
BaseLayout.cshtml
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
@RenderBody()
</body>
</html>
DashboardLayout.cshtml
@{
Layout = "BaseLayout.cshtml";
}
@await Html.Partial("_RightSidebar.cshtml")
@RenderBody()
DefaultPage.cshtml
@page
@{
Layout = "BaseLayout.cshtml";
}
DashboardPage.cshtml
@page
@{
Layout = "DashboardLayout.cshtml";
}
你可以把它加载到你的Dashboard.cshtml
里
@await Html.PartialAsync("_RightSidebar.cshtml")
见:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-2.1
假设您正在使用.net core 2.0,但我很确定上述内容也适用于1.0