简体   繁体   中英

Why doesn't my view load the jquery code from _Layout.cshtml but does when I add it lcoally to the view?

why doesn't my view load the Jquery that is inherited from the Layout.cshtml ?

When I put local link to the jquery in the view then it works but not otherwise.

_Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body style="padding-top:0px !important">
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" id="btncollapse" class="navbar-toggle" data-toggle="collapse" data-target="#navbarcollapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" target="_self" href="../Pages/frmHome.aspx">HerHim</a>
            </div>
            <div id="navbarcollapse" class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="Active"><a href="../Pages/frmHome.aspx">home</a></li>
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">About<span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="../Pages/frmHim.aspx" target="_blank">Me</a></li>
                            <li><a href="../Pages/frmHer.aspx" target="_blank">Her</a></li>
                            <li></li>
                        </ul>
                    </li>
                    <li><a href="/Stories/OurStory">Our Story</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer class="footer">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">
                        @*<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>*@
                    </div>

                </div>
            </div>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>

View:

@model HimHer.Models.Stories

@{
    ViewBag.Title = "Authenticate";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Stories</h4>
        <hr />

        <div>
            <div class="form-group">
                @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.UserName, new { @class = "form-control white" })
                </div>
            </div>


            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Password, new { @class = "form-control white" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" onclick="save();" value="Login" class="btn btn-default" />
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">

          function save() {


                var u = {
                    UserName: "Hunain",
                    Password: "123"
                };

                var users = JSON.stringify(u);

                $.ajax
                ({
                    url: '@Url.Action("Authenticate", "Users")',
                    type: 'POST',
                    contentType: "application/json; charset= utf-8",
                    data: users,
                    dataType: 'json',
                    success: function (results) {

                        alert(results.UserName);
                        //$('#myModal').modal('hide');
                    }
                });
            }
</script>

I tried my best but it doesn't work at all. Help me with it.

I check the page source after rendering but still and the script is below the ajax code.

This looks like a problem with the order of loading your scripts and the dependencies needed for that (in this case jQuery). When you look at the view source of the page, you can see that the view level scripts are loaded before jQuery is loaded.

This is happening because you are calling RenderBody in layout, which will render the markup rendered from your view to the place where it is called (just before the hr tag). But you are loading jQuery later, even after rendering the footer. So when razor render the js code from your view, that time ,jQuery is not available to the DOM yet.

To make sure that your view level code is executed after jQuery is loaded, you should be using Sections to render your page level script

So in your layout, include the needed files and after that, call the RenderSection method to execute the page level scripts

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
@RenderSection("scripts", required: false)

And in your view, keep all the page level scripts inside th section

@section scripts
{    
    <script>    
        $(function () {    
            if (jQuery) {
                 alert("jquery is loaded");
            }
            // you can use jQuery
        });    
    </script>
}

Now when razor render the layout, it will execute the scripts from your page/view where the RenderSection is called for scripts . Clearly we loaded jQuery before that. So everything will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM