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

时间:2012-05-05 11:11:40

标签: 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()

_Layout.cshtml - 实际网站主布局

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

<!doctype html>
<html>
<!-- actual site layout here -->
<body>
@RenderBody()
@RenderSection("javascriptLinks")
</body>
</html>

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

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

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

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

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

1 个答案:

答案 0 :(得分: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>

您的 _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)
}