9

给定视图层次结构: 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)。

4

1 回答 1

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)
}
于 2012-05-05T12:00:48.540 回答