【发布时间】:2014-04-27 18:55:23
【问题描述】:
@RenderSection 的用途是什么,它是如何发挥作用的?我了解捆绑包的作用,但我还没有弄清楚它的作用,它可能很重要。
@RenderSection("scripts", required: false)
也许是一个关于如何使用它的小例子?
【问题讨论】:
标签: asp.net-mvc
@RenderSection 的用途是什么,它是如何发挥作用的?我了解捆绑包的作用,但我还没有弄清楚它的作用,它可能很重要。
@RenderSection("scripts", required: false)
也许是一个关于如何使用它的小例子?
【问题讨论】:
标签: asp.net-mvc
如果你有这样的 _Layout.cshtml 视图
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
那么你就可以有一个这样的 index.cshtml 内容视图
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
必需表示使用布局页面的视图是否必须有脚本部分
【讨论】:
如果
(1) 你有一个像这样的 _Layout.cshtml 视图
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
(2) 你有 Contacts.cshtml
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
(3) 你有 About.cshtml
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
在您的布局页面上,如果 required 设置为 false "@RenderSection("scripts", required: false)",当页面呈现并且用户在 about 页面上时,contacts.js 不会呈现。
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
如果 required 设置为 true "@RenderSection("scripts", required: true)",当页面渲染并且用户在 ABOUT 页面时,contacts.js 仍然被渲染。
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
简而言之,当设置为 true 时,无论您在其他页面上是否需要它,它都会被渲染。如果设置为false,则仅在渲染子页面时才会渲染。
【讨论】:
true 时呈现关于页面时,你会得到一个Section not defined: "scripts".。
假设我有 GetAllEmployees.cshtml
<h2>GetAllEmployees</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
//Added my custom scripts in the scripts sections
@section Scripts
{
<script src="~/js/customScripts.js"></script>
}
另一个没有脚本的视图“GetEmployeeDetails.cshtml”
<h2>GetEmployeeByDetails</h2>
@Model.PageTitle
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
还有我的布局页面“_layout.cshtml”
@RenderSection("Scripts", required: true)
所以,当我导航到 GetEmployeeDetails.cshtml 时。我收到错误消息,即在 GetEmployeeDetails.cshtml 中没有要呈现的部分脚本。
如果我将 @RenderSection() 中的标志从 required : true 更改为 ``required : false`。这意味着渲染视图的@section 脚本中定义的脚本(如果存在)。否则,什么也不做。
改进的方法将在 _layout.cshtml
@if (IsSectionDefined("Scripts"))
{
@RenderSection("Scripts", required: true)
}
【讨论】:
这里是来自MSDN的Rendersection的定义
在布局页面中,呈现命名部分的内容。MSDN
在_layout.cs页面放
@RenderSection("Bottom",false)
这里渲染bootom部分的内容,并指定false布尔属性来指定是否需要该部分。
@section Bottom{
This message form bottom.
}
意思是如果你想在所有页面的底部分区,那么你必须在Rendersection方法中使用false作为第二个参数。
【讨论】: