A common way to improve the performance of your ASP.NET MVC project is to use Microsoft’s web optimization framework to bundle, and minify JavaScript files, and style sheets.

How to add System.Web.Optimization reference to your ASP.NET MVC project

1. Use the Nuget Package Manager to install the package Microsoft.AspNet.Web.Optimization

2. Add to the web.config in your Views folder the following key:

<add namespace="System.Web.Optimization"/>

Using the Web Optimization framework features in your project

Resources are bundled together (allowing to reduce the number of HTTP request made to the server) like this:

using System.Web.Optimization;
namespace AppSample
{
    public class BundleConfig
    {
       public static void RegisterBundles(BundleCollection bundles)
	        {
	            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
	                        "~/Scripts/jquery-{version}.js"));
				 bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/mysite.css"));
			}
	}
}

Remember to register your bundles in your Global.asax.cs file:

using System.Web.Optimization;
using System.Web.Routing;

namespace AppSample
{
    public class SampleApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
			//REGISTER YOUR BUNDLES
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
}

In your .cshtml files use the following methods:

 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/jquery")

That’s all. I hope it was of help 🙂

If you found this post useful you can subscribe to my blog (click at the follow button at the bottom ) so you can be notified of new posts.

Advertisements