ASP.NET MVC > Bundles

Create and use ScriptBundle in ASP.NET MVC

How to create and use a ScriptBundle in ASP.NET MVC?


Creating a Script bundle

JavaScript bundles can be created only in ~/App_Start/BundleConfig.cs page. To create a JavaScript bundle we use ScriptBundle class by passing virtual path as parameter in the constructor.

Once the instance has been created, we include the files to be added in this bundle. The files to include can be

  • the path of a file name
var ajaxHelperFile = new ScriptBundle("~/bundles/jQueryAjax");
ajaxHelperFile.Include("~/Scripts/jquery.unobtrusive-ajax.min.js");
  • multiple files path separted by comma
var myJsBundles = new ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js",
                   "~/Scripts/respond.js");

In the above code snippet, instead of instantiating and then including the file path, we have done both work in a single statement. We can follow the same approach as followed in the first point above.

  • The pattern of file path from a directory
var jQueryFiles = new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js");

Above bundle will get all file starting with “jquery-“ and any version in between and ends with “.js”.

Like “jquery-1.10.2.js” or “jquery-1.11.2.js” or “jquery-2.10.0.js” etc.

var jQueryValidate = new ScriptBundle("~/bundles/jqueryval").Include(
                  "~/Scripts/jquery.validate*");

Above bundle will get all files starting with “jquery.validate”.

Like “jquery.validate.min.js” or “jquery.validate.unobtrusive.js” etc.

To add the bundles created, we can add them into the BundleCollection object in the ~/App_Start/BundleConfig.cs page like below

var ajaxHelperFile = new ScriptBundle("~/bundles/jQueryAjax");
ajaxHelperFile.Include("~/Scripts/jquery.unobtrusive-ajax.min.js");
bundles.Add(ajaxHelperFile);
OR
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
            "~/Scripts/modernizr-*"));

Using Script bundle

To use the script bundler defined above, we can use @Script handler method Render

CODE FROM VIEW OR LAYOUT

@Scripts.Render("~/bundles/modernizr")

Where the string passed into the Render method is the virtual path specified exactly in the ~/App_Start/BundleConfig.cs file.

Calling above @Script.Render will render all files from the ~/Scripts folder starts with “modernizr-“ word as while creating and adding the bundle into the BundleCollection, “~/bundle/modernizr” was used for “~/Scripts/modernizr-*” files.

The output in the browser source code will be something like below as it could only found one .js file that starts with “modernizr- “ word. If more than one file starts with “modernizr-“, more than one <script> tag will get generated.

<script src="/Scripts/modernizr-2.6.2.js"></script>
 Views: 12361 | Post Order: 116



Write for us






Hosting Recommendations