2017年9月17日 星期日

[MVC] Layout and Section

  • Layout 
    • 主要建立網頁共用內容,如 html, css, javascript ... 等
    • 共用 Layout 目錄位置為:\\Views\Shared
    • @RenderBody method為:將 View 中內容插入 Layout
    • Step 1:創建一個空專案為 MVC,並且 Controllers 加入一個頁面
    • Step 2:新增檢視頁面,並勾選"建立成部分檢視"
    • Step 3:查看目錄資訊,會發現自動產生 _Layout.cshtml 與 _ViewStart.cshtml
      • _ViewStart.cshtml 為連結 View 與 Layout
      • 因此使用 _ViewStart.cshtml 定義 Layout,放在 Views 目錄下的 _ViewStart.cshtml 會在所有其它 View 執行之前先執行

      • 如開起 Demo index 頁面,會先讀取 _ViewStart.cshtml 並將頁面插入至 _Layout.cshtml 中 @RenderBody 
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
  • Section 
    • 先前有介紹 Bundling and Minification 主要是用在 _Layout,因此會使用在每個頁面中,但有頁面需客制化或需撰寫特定的 JavaScript,就可使用 Section 
    • Step 1. 在 View 中定義 Section ,使用 @section 指示
      • 下列定義 styles 與 scripts

@section styles {
    <style>
        h1{
            background-color:greenyellow;
        }
    </style>
}

<h1 id="toptitle">Lyndon</h1>

@section scripts {
    <script>
        $(function () {
            $('#toptitle').text(function (i, oldText) {
                return 'Hello' + oldText;
            });
        });
    </script>
}
    • Step 2. 將 Section 加入 Layout
      • 使用 RenderSection Method 在 _Layout.cshtml
      • required: false 表示 View 可不用定義 section 區段
    • Step 3. 可見到此結果
  • 恆逸

沒有留言:

張貼留言