Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 4 Bundles

Lots of code that I have seen reference this:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Which is great, and it works...if "something" is included. Do I have to add a reference to get these? Use NuGet? Copy a DLL? Where does this come from?

When I run my project, I get a 404 for that resource.

like image 585
Matt Dawdy Avatar asked Feb 19 '13 02:02

Matt Dawdy


People also ask

What are bundles in ASP.NET MVC?

Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.

What is bundle and minification in MVC?

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

How is bundling done in MVC?

Bundling and minification techniques were introduced in MVC 4 to improve request load time. Bundling allows us to load the bunch of static files from the server in a single HTTP request. In the above figure, the browser sends two separate requests to load two different JavaScript file MyJavaScriptFile-1.

What are the two types of bundles in MVC 5?

JavaScript Bundles and Stylesheet bundles are different. All the file content is minified in size by removing extra spaces, commented texts and shortening the names of scoped variables. It becomes easy for developer to reference a set of files through single file thus making the code clean and more readable.


2 Answers

You need to create the bundle. This is often done in the App_Start\BundleConfig.cs file in your ASP.NET MVC 4 project. It is all explained in Bundling and Minification .

In the BundleConfig class you need something like this (this method should execute in Application_Start):

public static void RegisterBundles(BundleCollection bundles) {
  bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
              "~/Scripts/jquery-{version}.js"));

  bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
              "~/Scripts/jquery.unobtrusive*",
              "~/Scripts/jquery.validate*"));

  // ... more registrations ...
}

The javascript source files should exists in the Scripts folder. The tutorial linked above explains how minified versions are bundled in the release build etc.

like image 161
Martin Liversage Avatar answered Sep 28 '22 05:09

Martin Liversage


FYI - I have seen many examples of using Bundles in MVC, but most neglect to mention that the assemblies for this are in System.Web.Optimization.dll and you can get this from NuGet by adding the Microsoft ASP.NET Web Optimization Framework package.

like image 29
ProVega Avatar answered Sep 28 '22 05:09

ProVega