ASP.NET MVC - レイアウトの入れ子のメモ

今ごろですが Razor でレイアウトの入れ子を試してみたので、そのときの個人的なメモです。

スクリプト用として使うようなセクションは子のレイアウト(今回の場合は _SubLayout.cshtml)でもう一度定義する必要あると。そらそうか。

_MainLayout.cshtml

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
</head>
<body>
    <div>
        <h1>Main Layout</h1>
        @RenderBody()
    </div>
    @* よくあるスクリプト用のセクション *@
    @RenderSection("script", false)
</body>
</html>

_SubLayout.cshtml

@{
    // メインレイアウトを参照
    Layout = "~/Views/Shared/_MainLayout.cshtml";
}
@* スクリプト用のセクションを再定義 *@
@section script {
@RenderSection("script", false)
}
<div>
    <h2>Sub Layout</h2>
    @RenderBody()
</div>

Content.cshtml

@{
    // サブレイアウトを参照
    // 本当なら _ViewStart.cshtml に書くところだけど
    Layout = "~/Views/Shared/_SubLayout.cshtml";
}
@section script {
<script>
   document.addEventListener("DOMContentLoaded", function () {
       console.log("Content!!");
   });
</script>
}
<div>
    <h3>Content</h3>
</div>

実行結果

f:id:ichiroku11:20140119001159p:plain

参考

第7回 レイアウト/部分ビューでアプリ共通のデザインを定義 - @IT