0

I am trying to bundle a jquery file on a view which doesn't have layout as below

<html>
<head>
@section Scripts{
  <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/jquery")">
  </script>
}
<script type="text/javascript">
$(document).ready(function () {

The bundle config for the above is already written and is as below

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

Whenever I call the document.ready function I see a $ not defined exception which means that the scripts haven't loaded.

The same bundling is working perfectly when placed in a layout.cshtml under the same shared folder. Am I missing something?

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
TRR
  • 1,637
  • 2
  • 26
  • 43
  • I'd imagine the ordering of your scripts is wrong, i.e. your trying to use jquery before it's been loaded. Why would you want to load jquery not in the layout? It makes much more sense to load it upfront everytime – Liam May 26 '17 at 13:01
  • @Liam I only need jquery in this page and I am using that bundle. – TRR May 26 '17 at 13:02
  • Move your scripts section to above your other javascript imports then. To answer this properly we need to see how you render `scripts` and your other js files – Liam May 26 '17 at 13:03
  • OK, expanded the code. The scripting starts after bundling. – TRR May 26 '17 at 13:05
  • Also, If I add a reference to jquery script file using normal script tag as opposed to bundling, things seems to be working just fine. – TRR May 26 '17 at 13:07

2 Answers2

2

This is the problem line:

@section Scripts{

If you are not using a layout page, this section is not rendering (I'm surprised it wouldn't be throwing an error). Sections are only used for layout pages. If you want a page to work, get rid of the section and then put the jquery bundle script directly in the page.

You may also want to consider: Why scripts at the end of body tag

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • yeah, the dumbest copy paste issue I have ever done.. sometimes people say writing the code is better than copy-pasting. – TRR May 26 '17 at 13:37
-1

Use like this:

@Scripts.Render("~/bundles/jquery")
User3250
  • 2,961
  • 5
  • 29
  • 61