Reputation: 1088
I'm using ASP.NET MVC4... Out of the box _Layout.cshtml has
@Scripts.Render("~/bundles/jquery")
in it. Also I have the stock BundleConfig.cs which has a
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
in it. I have a script block like this in my Index.cshtml which is just a normal view.
<script src="@Url.Content("~/Scripts/ProductsIndex.js")" type="text/javascript"></script>
But the JQuery in that script does not run... However, if I put the following line in my Index.cshtml, (right next to the ProductsIndex.js script reference) then the JQuery runs fine.
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"> </script>
I know this is something simple, but given that _Layout.cshtml already references the JQuery library, shouldn't I be able to use JQuery without having to add it again to my Index.cshtml explicitly?
Upvotes: 2
Views: 6022
Reputation: 1088
What fixed the problem for me was moving the @Scripts.Render("~/bundles/jquery") statement from the bottom of the _Layout.cshtml to the top. By default, Microsoft put this render statement below the footer. I moved it into the section along with the @Scripts.Render("~/bundles/modernizr") and then the script in my index.cshtml started working.
So apparently the issue was that when my script inside index.cshtml tried to execute, JQuery was not yet loaded because it was at the bottom of the page.
Upvotes: 1
Reputation: 107508
You could simply put the actual filename in the bundle config for query and remove the tokenized version:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-1.8.2.min.js"));
If you aren't building your application in Release mode (or have <compilation debug="true" />
in your web.config), then the existing bundle configuration might not find your minified (.min.js) version of jQuery.
Read about the bundling feature and how it automatically switches between unminified and minified versions of scripts based on build configuration here.
Upvotes: 0