Search code examples
asp.net-mvcbundling-and-minification

MVC Bundling on views without layout pages


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?


Solution

  • 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