我在本节中定义了此部分 _Layout.cshtml
@RenderSection("Scripts", false)
Run Code Online (Sandbox Code Playgroud)
我可以从视图中轻松使用它:
@section Scripts {
@*Stuff comes here*@
}
Run Code Online (Sandbox Code Playgroud)
我正在努力的是如何从局部视图中获取本节内注入的一些内容.
我们假设这是我的视图页面:
@section Scripts {
<script>
//code comes here
</script>
}
<div>
poo bar poo
</div>
<div>
@Html.Partial("_myPartial")
</div>
Run Code Online (Sandbox Code Playgroud)
我需要Scripts从_myPartial局部视图中注入部分内容.
我怎样才能做到这一点?
我在这个主题上看了几篇帖子:
它似乎总是有问题的.然而,他们都很老了,所以想知道事情是否有所改变.
基本上我有一个主布局,以及3种不同的主体模板,基于它是什么类型的页面.例如:
_Layout.cshtml
<html lang="en">
<head>
</head>
<body style="padding: 50px 0;">
<header class="navbar navbar-default navbar-fixed-top" role="banner">
@Html.Partial("_MenuPartial")
</header>
<ol class="breadcrumbs">
@RenderSection("breadcrumbs", true);
</ol>
<section>
@RenderBody();
</section>
<footer class="navbar navbar-default navbar-fixed-bottom">
@Html.Partial("_FooterPartial")
</footer>
@Html.Partial("_ScriptInitPartial")
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
_LayoutForEdit.cshtml
<div class="panel panel-primary">
<div class="panel-body">
<div class="col-lg-2">
<ul class="nav nav-pills nav-stacked">
@RenderSection("tabs", true)
</ul>
</div>
<div class="col-lg-10">
<div class="tab-content">
@RenderBody()
</div>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-primary" data-bind="enable: Entity.isValid, click: save">Save</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在,这在调用时呈现正常.几乎.
部分的呈现必须在它看起来的子布局中.如果我尝试将面包屑放入其中 …
我找不到使 @section 和 @RenderSection() 使用多级布局的方法。在我的项目中,我定义了布局的层次结构:
〜/ Views / Shared / _Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta ... />
<meta ... />
<link href="..." rel="stylesheet" type="text/css" />
<link href="..." rel="stylesheet" type="text/css" />
@RenderSection("Stylesheet", false)
</head>
<body>
<!-- lots of markup -->
@RenderBody()
<!-- more markup -->
<script src="..." type="text/javascript" />
<script src="..." type="text/javascript" />
@RenderSection("JavaScript", false)
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
~/Views/Shared/_BaseLayout.cshtml(没有 JavaScript 或样式表部分的定义):
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- lots of markup -->
@RenderBody()
Run Code Online (Sandbox Code Playgroud)
~/Views/Shared/_CreateEditLayout.cshtml(同样,没有 JavaScript 或样式表的定义):
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- …Run Code Online (Sandbox Code Playgroud)