專案中的各個Page會被插入到_Layout.cshtml裡@RenderBody()的位置,與主版面整合。若Page中的某段程式不想被放在body內時,可以使用Section及RenderSection改變程式碼在_Layout.cshtml中的插入位置。
本次的使用情境是想要在頁面中加入JavaScript檔案,但想要讓他在_Layout.cshtml的最尾端才被讀取,故使用Section及RenderSection改變程式碼的插入位置。
建立Section區塊
在Index.cshtml
中加入Section區塊,將要插入的程式碼放在大括弧中
<div id="index">
<section class="section">
...
</section>
</div>
@section Scripts {
<script type="module" src="~/js/Index.min.js" asp-append-version="true"></script>
}
@section後面的Scripts可以自定義名稱,必須對應到RenderSection函式內傳入的名稱
使用RenderSection插入程式碼
在_Layout.cshtml
中選擇一個風水寶地將RenderSection加入程式中,用以插入在Section中的程式碼
<body>
<div id="app">
<header class="header">
...
</header>
</div>
@RenderBody()
<script type="module" src="~/js/App.min.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>