Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jquery doesn't work on a page defined in layout

I have a razor layout and it loads css jquery etc.
When I add controller action view I set layout to be _Layout.cshtml
But jquery doesn't work in that page.
So I have to add @Scripts.Render("~/bundles/jquery") in each view.
Why imported jquery is not inherited from _Layout.cshtml? Is it normal?

like image 321
1110 Avatar asked Sep 17 '13 21:09

1110


People also ask

Which code is used to add jQuery in _layout Cshtml file?

The jquery code is in _Layout,cshtml.

How do you solve is not defined error?

Answer: Execute Code after jQuery Library has Loaded The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.

HOW include jQuery in ASP NET MVC?

After the ASP.NET MVC Framework is installed a new ASP.NET MVC Web Application project should be created. Next, download jQuery, get the Packed or Minified version and place it into the Content folder of the the new web application project. Add a reference to the jQuery file put in the Content folder.


1 Answers

This should be near the bottom of _Layout.cshtml:

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

This should be in your child view:

@section scripts {
    @Scripts.Render("~/scripts/jquery.infinitescroll.js") // Or some other script
}

All your scripts (that reference jquery) in your child views need to be in the scripts section, not placed in the body of the page. That includes any script tags that want to make use of jquery as well. For example, one of my pages has the following:

@section scripts {
    @Scripts.Render("https://maps.googleapis.com/maps/api/js?key=&sensor=false")
    <script src="~/scripts/google-maps-3-vs-1-0.js"></script>
    <script>
        Stuff here
    </script>
}
like image 170
Robert McKee Avatar answered Oct 23 '22 01:10

Robert McKee