how to call javascript on layout mvc

2019-06-03 07:10发布

问题:

I try to run a basic javascript in all my pages (before load another html code), then I add my js function to _Layout.cshtml but doesn't work (I don't how is correct way to do it). Thanks in advance.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script type="text/javascript">
            $(document).ready(function () {
                alert("Do something");
            });
        </script>
    </head>
    <body>

        <div data-role="page" data-theme="b">
            <div data-role="content">
                @RenderBody()
            </div>
        </div>

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

回答1:

@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")

must be before

    <script type="text/javascript">
        $(document).ready(function () { // JQuery not loaded here, $ is undefined
            alert("Do something");
        });
    </script>