Bundling in ASP.Net 4.0

Updated 8/29/2018 - Formatted
 
In ASP.Net 4.5 there is a new feature called "Bundling". Now you might ask whad does it do?. Bundling bundles multiple files into a single file. For example if you want to use two CSS and five jQuery files in your page and all are in the styles and scripts folder.  What you will do? , you provide the path for all CSS and jqery file in your page like:
 
For CSS file:
  1. <link href='<%= ResolveUrl("~/Styles/Test1.css")%>' rel="stylesheet" type="text/css" />  
  2. <link href='<%= ResolveUrl("~/Styles/Test2.css")%>' rel="stylesheet" type="text/css" />  
For jQuery file:
  1. <script src='<%= ResolveUrl("~/Scripts/Test1.js")%>' type="text/javascript"></script>  
  2. <script src='<%= ResolveUrl("~/Scripts/Test2.js")%>' type="text/javascript"></script>  
  3. <script src='<%= ResolveUrl("~/Scripts/Test3.js")%>' type="text/javascript"></script>  
  4. <script src='<%= ResolveUrl("~/Scripts/Test4.js")%>' type="text/javascript"></script>  
  5. <script src='<%= ResolveUrl("~/Scripts/Test5.js")%>' type="text/javascript"></script>  
Now when you load your page then seven requests will go to the server. Bundling will reduce the number of requests sent to the server. You can do this easly in 4.5.
 
In this article I will tell you how to use Bundling in ASP.Net 4.0.
 
By the preceding description about Bundling you can easily understand that Bundling is used for performance optimization.
 
To use the Bundling feature in ASP.Net 4.0 you will need the following two DLLs:
  1. System.Web.Optimization.dll
  2. WebGrease.dll
Now add references for both DLLs in your web.
 
image1.png 
 
In the following sample code I am using two CSS files in the content folder so both files are bundled for the single request.
 
Now add the following line of code in the Application_Start event of global.asax to register the bundle.
  1. RegisterBundles(System.Web.Optimization.BundleTable.Bundles);  
  2.  BundleTable.EnableOptimizations = true;   
Now in web.config add the following line to give the reference of the added DLL in your web.config file.
  1. <system.web>  
  2.         <compilation debug="true" targetFramework="4.0" />  
  3.       <pages>  
  4.         <namespaces>  
  5.           <add namespace="System.Web.Optimization" />  
  6.         </namespaces>  
  7.         <controls>  
  8.           <add assembly ="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />  
  9.         </controls>  
  10.      </pages>  
  11. </system.web>  
Now add the following line given below in your masterpage head section.
  1. <%: System.Web.Optimization.Styles.Render("~/Content/css") %>  
Now you can check on your page, it bundles both files in "css?v=".
 
Image2.png 
 
And you can see only two requests went to server one for the aspx page and another for the CSS.
 
Image3.png 


Similar Articles