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.
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.
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.)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With