MVC:如何从父(主)视图(布局视图)中使用(渲染)部分?

Shr*_*ike 9 asp.net-mvc

给定视图层次结构:Index.cshtml - > _Layout.cshtml - > _MasterLayout.cshtml:

_MasterLayout.cshtml - 我想在主布局中使用的部分集(下面)

@section javascriptLinks {
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script>
}
@RenderBody()
Run Code Online (Sandbox Code Playgroud)

_Layout.cshtml - 实际站点主布局

@{
  Layout = "~/Views/Shared/_MasterLayout.cshtml";
}

<!doctype html>
<html>
<!-- actual site layout here -->
<body>
@RenderBody()
@RenderSection("javascriptLinks")
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Index.cshtml - 一些具体的页面特定标记

拆分_Layout.cshtml和_MasterLayout.cshtml的想法是代码共享.我有一种库/框架,_MasterLayout属于这个库._Layout.cshtml是具体的应用程序站点主布局.

不幸的是,这种架构不起作用.在渲染过程中,_Layout.cshtml将不会看到_MasterLayout.cshtml中的部分.

有没有办法在这种情况下使用部分(从父视图中获取它们而不是从子视图中获取)?

我能看到的一个可能的解决方案是在_MasterLayout.cshtml中为每个部分创建单独的页面,并在_Layout中调用@RenderPage.但是,我想拥有一个共享资产(_MasterLayout.cshtml).

Wah*_*tar 5

尝试撤消操作.我的意思是这样的:

你的_MasterLayout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @RenderSection("HeadSection", true)
    <title>@ViewBag.Title</title>
</head>
<body>
@RenderBody()

// ...... 
// You could put your general scripts here
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script>
// Put true to enforce the sub layout to define Scripts section
    @RenderSection("Scripts", true)
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

你的_Layout.cshtml:

@{ Layout = "~/Views/_Shared/_LayoutMain.cshtml"; }
@section HeadSection{
    // any thing you want
    @RenderSection("HeadSection", false)
}
    @RenderBody()
// ...... 
// Put false to make Scripts section optional
@section Scripts{
    @RenderSection("Scripts", false)
}
Run Code Online (Sandbox Code Playgroud)