LoginSignup
7
13

More than 5 years have passed since last update.

ASP.NET MVC Viewに関するメモ

Last updated at Posted at 2017-01-29

ASP.NET MVCのViewに関するメモです。

Viewが表示される基本的な流れ

HomeControllerのIndex Actionが呼ばれたとき下記のような流れで処理されます。

  1. /Views/_ViewStart.chtmlが読み込まれる
  2. /Views/Shared/_Layout.chtmlが読み込まれる(1.で指定しているから)
  3. 2.の_Layout.chtml中の@RenderBody()が呼ばれる(2. に記述されているから)
  4. /Views/Home/Index.chtmlが呼ばれる
  5. 必要に応じて@RenderSection()が呼ばれる

テンプレートを変更してみる

BootstrapのGet Startedのサンプルコードをベースに下記のようなテンプレートファイルを作成してみました。CDN好きなので外部ライブラリは基本CDNを利用しています。

テンプレートの用意

下記の内容を/Views/Shared/_Baselayout.chtmlとして保存します。

_Baselayout.chtml
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@ViewBag.Title</title>
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container body-content">
        <header>
            header
        </header>
        <main>
            <h1>Main!</h1>
            @RenderBody()
        </main>
        <footer>
            footer
        </footer>
    </div>
    <!-- script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

標準テンプレートの変更

/Views/_ViewStart.chtmlの内容を下記のように書き換えます。

_ViewStart.chtml
@{
    Layout = "~/Views/Shared/_Baselayout.cshtml";
}

これで完了です。

番外編

カスタムCSSを置いて~bundleを利用せず利用したい

chtmlのテンプレートの中で~bundleとかを使うのは好きでないので普通に/css/my.cssとかで指定したい。その際はどこが/になるのかを確認。

結論→プロジェクト直下を/と認識するらしい。
例えばテンプレートに下記のように書いた場合。

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/css/my.css">
</head>
<body>
</body>
</html>

プロジェクト直下にCSSというフォルダを作ればそこが/CSSとして認識される。

7
13
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
7
13