回答:
もし
(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)"、ページがレンダリングされ、ユーザーが約ページにいる場合、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 STILLがレンダリングされます。
<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>
IN SHORTでは、trueに設定すると、他のページでそれが必要かどうかにかかわらず、とにかくレンダリングされます。falseに設定すると、子ページがレンダリングされるときにのみレンダリングされます。
ここからレンダーセクションの定義 MSDN
レイアウトページで、名前付きセクションのコンテンツをレンダリングします。MSDN
_layout.csページに
@RenderSection("Bottom",false)
ここでは、bootomセクションのコンテンツをレンダリングしfalse
、セクションが必要かどうかを指定するブールプロパティを指定します。
@section Bottom{
This message form bottom.
}
つまり、すべてのページの下部セクションにしたい場合は、Rendersectionメソッドの2番目のパラメーターとしてfalseを使用する必要があります。
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()
from required : true
から `` required:false` に変更すると、これは、ビューの@sectionスクリプトで定義されているスクリプトが存在する場合はレンダリングすることを意味します。そして、洗練されたアプローチは_layout.cshtmlにあります
@if (IsSectionDefined("Scripts"))
{
@RenderSection("Scripts", required: true)
}
Section not defined: "scripts".
必要なフラグを設定すると、Aboutページをレンダリングするときにが表示されることがわかりますtrue
。