如何在特定视图中加载PartialView?

时间:2018-09-03 10:25:21

标签: asp.net asp.net-core

假设在我的文件夹Dashboard中有一个名为PartialView的{​​{1}},我只需要将此_RightSidebar包括在_PartialView中,所以我m仅在用户位于DashBoard的视图内时才寻找加载_RightSidebar的方法。

实际上,我将Dashboard装入了_RightSidebar内,但是如果我不在_Layout中,则会收到错误消息,因为Dashboard只是其中的一部分_RightSidebar(我想避免为每个仪表板视图创建冗余代码)。

Dashboard已经存在相同的机制,但是我找不到类似于Section的东西,有人知道该怎么做吗?

2 个答案:

答案 0 :(得分:1)

在布局中,只需定义一个可选的部分,然后在“仪表板”页面上,在此部分中渲染部分视图:

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";
}

答案 1 :(得分:0)

您可以将其加载到您的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版中使用