LoginSignup
7
9

More than 5 years have passed since last update.

ASP.NET MVC Razor メモ スクリプト読み込み

Posted at

Razorの各ページでスクリプトを読み込む方法が良く分かっていなくて調べた時のメモ。

共通レイアウト_Layout.cshtmlを読み込んでいる場合

_Layout.cshtml
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

各ビューのページで以下のように@section scriptsで記載する。

Addpage.cshtml
@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            alert("hello world");
        });
    </script>
}

App_Startフォルダ内のBundleConfig.csに以下のように定義されている。

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

@section scriptsではなく以下のように定義すると呼び出されない。

Addpage.cshtml
<script type="text/javascript">
        $(document).ready(function () {
            alert("hello world");
        });
</script>

共通レイアウト_Layout.cshtmlを読み込んでいない場合

Addpage.cshtml

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")

<script type="text/javascript">
        $(document).ready(function () {
            alert("hello world");
        });
</script>

参考にしたサイト

https://qiita.com/longk/items/180bb672d33d71be6f60
http://09.hatenadiary.jp/entry/2013/11/19/103525

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