10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET MVC 基礎 その1【テンプレート、共通パーツ】

Last updated at Posted at 2019-09-25

アジェンダ

  • テンプレート構造
  • Viewが表示される流れ
  • テンプレート類
  • _Layout.cshtml
  • _ViewStart.cshtml
  • 共通パーツ

テンプレート構造

├ Views
├ Shared (共通パーツ格納ディレクトリ)
│ ├ _Layout.cshtml(アプリの既定のレイアウト)
│ ├ _Header.cshtml
│ └ _Footer.cshtml
└ _ViewStart.cshtml (各ビューの前に実行する処理を記載する)

Viewが表示される流れ

  1. /Views/_ViewStart.chtmlが読み込まれる
  2. /Views/Shared/_Layout.chtmlが読み込まれる(1.で指定しているから)
    3.の_Layout.chtml中の@RenderBody()が呼ばれる(2. に記述されているから)
    @RenderBody()はテンプレートに1箇所のみ
  3. 必要に応じて@RenderSection()が呼ばれる
    @RenderSection()は複数箇所でも可

テンプレート類

_Layout.cshtml

アプリの既定のレイアウト。
ファイル名の先頭に「_(パーシャル)」を付ける。

_layout.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

@RenderBody() とは
このテンプレートを使ったページの本体を出力する。

@RenderSection()とは
@RenderSection(セクション名, required: 必須かどうか)のように引数を用いて、メインのボディ部分以外も、カスタマイズできるようにしている。

具体的に言うと。。

■レイアウトでscriptsセクションを呼び出すように指定して

_layout.html
@RenderSection("scripts", required: false)

■各ページでscriptsセクションを用意してあげる。

index.html
@section scripts{
<script type="text/javascript">
    $(function(){
        //index.htmlで使うjsの処理を記述
    });
</script>
}

_ViewStart.cshtml

最初に実行する処理を記載する。

_ViewStart.html
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
10
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?