Bundling in MVC4

Bundling in MVC4

In today's world we tend to create sophisticated websites with rich content using multiple CSS or CSS3 files and jQuery plugins or JavaScript files that help us to display rich content on the webpage and it gives a better look and feel to the application pages that in turn increases the user's attraction towards the websites. But a problem arises when the user tries to request pages that are enriched with multiple CSS or scripts files or images. What happens behind the scenes is that for every stylesheet or script file or image used on the page the request from the browser to the server is made for downloading the item in the user's browser that decreases the performance of the page. For instance let's say that there are 5 CSS files and 7 scripts files used on the page. Then in this case there would be approximately 13 to 14 requests made for each CSS and scripts files and for accessing the page (12 requests for CSS and Script and 1 request for accessing the requested page and 1 more for parsing the requested page). Although the latest browser are now supporting caching features but the problem is that at least for the first request from the browser to the server it would use a lot of bandwidth on the server and if your application is used by multiple user's then in that case it would cause a serious performance issue. Using MVC we can reduce this unwanted number of calls from the browser to the server using the feature named “Bundling”.

Bundling helps us to manage our stylesheets and scripts files in a more elegant way. It also helps in reducing the network traffic by optimizing the request processing (in other words reducing the number of calls for downloading the scripts/CSS files) from the user to the server and vice versa. Bundling helps us to merge all the files in a single request from the server to the browser. As we all know now that when there are many requests and calls from the user to the server the performance of the server is reduced due to use of many server resources that in turn affects the performance of the application. This is where features like bundling acts as a “Boon” in the application development. Whenever you create a new project in MVC and you select the project template other than “Empty” you get many scripting files that consist of jQuery and its supporting files like validate, unobtrusive and so on. You may also find the script files exist in two flavors like jquery-{version}.js and jqyery-{version}.min.js and so on.

A JavaScript file is a scripting file that is mostly used in the development environment because it helps us to debug the file more efficiently then the minified version. It contains proper syntax with white spaces and comments and more user-friendly names given to variables/functions wherever required and it is very much easy to debug it like a normal JavaScript file. If you try to look at the minified version of the jquery-{version}.min.js file then in this case you may find a single line of entry stretched from left to right with no spaces or comments and no proper syntax because of which it becomes difficult for the developer to debug the minified script file. The advantage of using a minified version in the application is that it is lightweight (it causes less bandwidth and less download time on the server to deliver it to the client browser) that's why it used in the deployment process.

Let's proceed with the demo application. For this I'm selecting the project template as “Basic”.

When you create a new project you'll find many script files added to the application. Some of them may be a .js file and some them may be .min.js files. In the case of a knockout-{version}.js file the convention is a little bit different. You'll find the name as “knockout-2.1.0.debug.js” and “knockout-2.1.0.js” where the “knockout-2.1.0.debug.js” file is used in development and “knockout-2.1.0.js” is used in the deployment process.

Let's add a new model with the name “Employee.cs”; the following is the code snippet for it.

  1.    //The adavantage of using Bind at the model level is that it will be applied to all those view where this model is used  
  2.     [Bind(Exclude = "Id")]  
  3.     public class Employee  
  4.     {  
  5.         [Key]  
  6.         public int Id { getset; }  
  7.   
  8.         [Required(ErrorMessage = "Name is Required")]  
  9.         public string Name { getset; }  
  10.   
  11.         [Required(ErrorMessage = "Address is Required")]  
  12.         public string Address { getset; }  
  13.   
  14.         [Required(ErrorMessage = "Salary is Required")]  
  15.         public float Salary { getset; }  
  16.     }  
I've added two new folders to the application with the names “Concrete” and “Abstract” that will store the C# files and interfaces. I've added a new interface named “IEmployeeRepository” within the Abstract folder. The following is the code snippet
IEmployeeRepository.cs”:
  1. public interface IEmployeeRepository  
  2. {  
  3.     IQueryable<Employee> Employees { get; }  

  4.     void AddEmployee(Employee objEmployee);  
  5.   
  6.     void DeleteEmployee(int eid);  
  7. }  
Inside the Concrete folder we've added two new classes. Here is the code snippet for it.

“DummyDbContext.cs”
  1. /// <summary>  
  2.     /// This class will act similar to that of DbContext class by provinding features such as adding a new employee, deleting the existing employee  
  3.     /// or providing list of all employees etc.  
  4.     /// </summary>  
  5.     public class DummyDbContext  
  6.     {  
  7.         private IList<Employee> _lstEmployees;  
  8.   
  9.         public DummyDbContext()  
  10.         {  
  11.             _lstEmployees = new List<Employee>();  
  12.             _lstEmployees.Add(new Employee() { Id = CreateIdentity(), Name = "Vishal Gilbile", Address = "Andheri", Salary = 25000 });  
  13.             _lstEmployees.Add(new Employee() { Id = CreateIdentity(), Name = "Rahul Bandekar", Address = "Bandra", Salary = 18000 });  
  14.             _lstEmployees.Add(new Employee() { Id = CreateIdentity(), Name = "Jack Fernandis", Address = "Santacruz", Salary = 30000 });  
  15.             _lstEmployees.Add(new Employee() { Id = CreateIdentity(), Name = "Lincy Pullan", Address = "Borivali", Salary = 45000 });  
  16.             _lstEmployees.Add(new Employee() { Id = CreateIdentity(), Name = "Sunny D'Souza", Address = "Vasai", Salary = 50000 });  
  17.         }  
  18.   
  19.         /// <summary>  
  20.         /// This function is used for creating an identity value for the newly added record in the list  
  21.         /// </summary>  
  22.         /// <returns></returns>  
  23.         private int CreateIdentity()  
  24.         {  
  25.             if (_lstEmployees.Count == 0)  
  26.                 return 1;  
  27.             else  
  28.             {  
  29.                 return _lstEmployees[_lstEmployees.Count - 1].Id + 1;  
  30.             }  
  31.         }  
  32.   
  33.         public IQueryable<Employee> Employees  
  34.         {  
  35.             get  
  36.             {  
  37.                 return _lstEmployees.AsQueryable();  
  38.             }  
  39.         }  
  40.   
  41.   
  42.         public void AddEmployee(Employee objEmployee)  
  43.         {  
  44.             objEmployee.Id = CreateIdentity();  
  45.             _lstEmployees.Add(objEmployee);  
  46.         }  
  47.   
  48.         public void DeleteEmployee(int empID)  
  49.         {  
  50.             int idx = _lstEmployees.IndexOf(_lstEmployees.Where(x => x.Id == empID).FirstOrDefault());  
  51.             if (idx >= 0)  
  52.             {  
  53.                 _lstEmployees.RemoveAt(idx);  
  54.             }  
  55.         }  
  56.     }  
“EmployeeRepository.cs”
  1. public class EmployeeRepository : IEmployeeRepository  
  2. {  
  3.     DummyDbContext objDbContext = new DummyDbContext();  

  4.     public IQueryable<Employee> Employees  
  5.     {  
  6.         get { return objDbContext.Employees; }  
  7.     }  
  8.   
  9.     public void AddEmployee(Employee objEmployee)  
  10.     {  
  11.         objDbContext.AddEmployee(objEmployee);  
  12.     }  
  13.   
  14.     public void DeleteEmployee(int eid)  
  15.     {  
  16.             objDbContext.DeleteEmployee(eid);  
  17.     }  
  18. }  
Now let's add a new controller to the application with the name “Home”. Before moving further we've installed the Unity.Mvc3 package within our application using the package console to get the benefit of “Dependency Injection”.

We've updated the newly added file named BootStrapper.cs (that we get after installing the unity.mvc3 package). the following is the code snippet that we added to the BootStrapper.cs file.
  1. public static class Bootstrapper  
  2. {  
  3.     public static void Initialise()  
  4.     {  
  5.         var container = BuildUnityContainer();  
  6.   
  7.         DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
  8.     }  
  9.   
  10.     private static IUnityContainer BuildUnityContainer()  
  11.     {  
  12.         var container = new UnityContainer();  
  13.   
  14.         // register all your components with the container here  
  15.         // it is NOT necessary to register your controllers  
  16.               
  17.         // e.g. container.RegisterType<ITestService, TestService>();    
  18.             
  19.         container.RegisterType<IEmployeeRepository, EmployeeRepository>();  
  20.   
  21.         return container;  
  22.     }  
  23. }  
Also we need to register the BootStarpper.cs file in the Global.asax file. The following is the line of code that you need to add to the Global.asax file inside the Application_Start function:
  1. //register the dependency resolver with the application  
  2.  Bootstrapper.Initialise();  
“HomeController.cs”
  1. public class HomeController : Controller  
  2. {  
  3.     EmployeeRepository _repository = new EmployeeRepository();  
  4.     private IEmployeeRepository _repository = null;  
  5.   
  6.     public HomeController(IEmployeeRepository repository)  
  7.     {  
  8.         this._repository = repository;  
  9.     }  
  10.   
  11.     public ActionResult Index()  
  12.     {  
  13.         return View(_repository.Employees);  
  14.     }  
  15. }  
Now let's try to create a view for the index function with scaffolding option selected to “List”.
  1. @model IEnumerable<BundlingDemo.Models.Employee>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5. <h2>  
  6.     Index</h2>  
  7.   <link rel="Stylesheet" type="text/css" href="../../Content/MyStyle.css" />  
  8.     <link rel="Stylesheet" type="text/css" href="../../Content/Site.css" />  
  9.     <script type="text/javascript" src="../../Scripts/jquery-1.7.1.js"></script>  
  10.     <script type="text/javascript" src="../../Scripts/jquery.unobtrusive-ajax.js"></script>  
  11.     <script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>  
  12.     <script type="text/javascript" src="../../Scripts/modernizr-2.5.3.js"></script>  
  13.     <script type="text/javascript" src="../../Scripts/jquery.validate.unobtrusive.js"></script>  
  14.   
  15. <p>  
  16.     @Html.ActionLink("Create New", "Create")  
  17. </p>  
  18. <div class="customTable">  
  19.     <table>  
  20.         <tr>  
  21.             <td>  
  22.                 @Html.DisplayNameFor(model => model.Id)  
  23.             </td>  
  24.             <td>  
  25.                 @Html.DisplayNameFor(model => model.Name)  
  26.             </td>  
  27.             <td>  
  28.                 @Html.DisplayNameFor(model => model.Address)  
  29.             </td>  
  30.             <td>  
  31.                 @Html.DisplayNameFor(model => model.Salary)  
  32.             </td>  
  33.             <td>  
  34.             </td>  
  35.         </tr>  
  36.         @foreach (var item in Model)  
  37.         {  
  38.             <tr>  
  39.                 <td>  
  40.                     @Html.DisplayFor(modelItem => item.Id)  
  41.                 </td>  
  42.                 <td>  
  43.                     @Html.DisplayFor(modelItem => item.Name)  
  44.                 </td>  
  45.                 <td>  
  46.                     @Html.DisplayFor(modelItem => item.Address)  
  47.                 </td>  
  48.                 <td>  
  49.                     @Html.DisplayFor(modelItem => item.Salary)  
  50.                 </td>  
  51.                 <td>  
  52.                     @Html.ActionLink("Delete", "Delete", new { id = item.Id })  
  53.                 </td>  
  54.             </tr>  
  55.         }  
  56.     </table>  
  57. </div>  
Our index view is using a set of CSS classes that are a newly created file with the name myStyle.css and also some jQuery script files. The following is the code snippet for the MyStyle.css:
  1. .customTable  
  2. {  
  3.     margin0px;  
  4.     padding0px;  
  5.     width100%;  
  6.     box-shadow: 10px 10px 5px #888888;  
  7.     border1px solid #000000;  
  8.     -moz-border-radius-bottomleft: 14px;  
  9.     -webkit-border-bottom-left-radius: 14px;  
  10.     border-bottom-left-radius: 14px;  
  11.     -moz-border-radius-bottomright: 14px;  
  12.     -webkit-border-bottom-right-radius: 14px;  
  13.     border-bottom-right-radius: 14px;  
  14.     -moz-border-radius-topright: 14px;  
  15.     -webkit-border-top-right-radius: 14px;  
  16.     border-top-right-radius: 14px;  
  17.     -moz-border-radius-topleft: 14px;  
  18.     -webkit-border-top-left-radius: 14px;  
  19.     border-top-left-radius: 14px;  
  20. }  
  21. .customTable table  
  22. {  
  23.     border-collapsecollapse;  
  24.     border-spacing0;  
  25.     width100%;  
  26.     height100%;  
  27.     margin0px;  
  28.     padding0px;  
  29. }  
  30. .customTable tr:last-child td:last-child  
  31. {  
  32.     -moz-border-radius-bottomright: 14px;  
  33.     -webkit-border-bottom-right-radius: 14px;  
  34.     border-bottom-right-radius: 14px;  
  35. }  
  36. .customTable table tr:first-child td:first-child  
  37. {  
  38.     -moz-border-radius-topleft: 14px;  
  39.     -webkit-border-top-left-radius: 14px;  
  40.     border-top-left-radius: 14px;  
  41. }  
  42. .customTable table tr:first-child td:last-child  
  43. {  
  44.     -moz-border-radius-topright: 14px;  
  45.     -webkit-border-top-right-radius: 14px;  
  46.     border-top-right-radius: 14px;  
  47. }  
  48. .customTable tr:last-child td:first-child  
  49. {  
  50.     -moz-border-radius-bottomleft: 14px;  
  51.     -webkit-border-bottom-left-radius: 14px;  
  52.     border-bottom-left-radius: 14px;  
  53. }  
  54. .customTable tr:hover td  
  55. {  
  56.     background-color#ffaaaa;  
  57. }  
  58. .customTable td  
  59. {  
  60.     vertical-alignmiddle;  
  61.     background-color#ffffff;  
  62.     border1px solid #000000;  
  63.     border-width0px 1px 1px 0px;  
  64.     text-alignleft;  
  65.     padding7px;  
  66.     font-size10px;  
  67.     font-familyArial;  
  68.     font-weightnormal;  
  69.     color#000000;  
  70. }  
  71. .customTable tr:last-child td  
  72. {  
  73.     border-width0px 1px 0px 0px;  
  74. }  
  75. .customTable tr td:last-child  
  76. {  
  77.     border-width0px 0px 1px 0px;  
  78. }  
  79. .customTable tr:last-child td:last-child  
  80. {  
  81.     border-width0px 0px 0px 0px;  
  82. }  
  83. .customTable tr:first-child td  
  84. {  
  85.     background: -o-linear-gradient(bottom#ff5656 5%, #7f0000 100%);  
  86.     background: -webkit-gradient( linear, left topleft bottom, color-stop(0.05#ff5656), color-stop(1#7f0000) );  
  87.     background: -moz-linear-gradient( center top#ff5656 5%, #7f0000 100% );  
  88.     filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff5656", endColorstr="#7f0000");  
  89.     background: -o-linear-gradient(top,#ff5656,7f0000);  
  90.     background-color#ff5656;  
  91.     border0px solid #000000;  
  92.     text-aligncenter;  
  93.     border-width0px 0px 1px 1px;  
  94.     font-size14px;  
  95.     font-familyArial;  
  96.     font-weightbold;  
  97.     color#ffffff;  
  98. }  
  99. .customTable tr:first-child:hover td  
  100. {  
  101.     background: -o-linear-gradient(bottom#ff5656 5%, #7f0000 100%);  
  102.     background: -webkit-gradient( linear, left topleft bottom, color-stop(0.05#ff5656), color-stop(1#7f0000) );  
  103.     background: -moz-linear-gradient( center top#ff5656 5%, #7f0000 100% );  
  104.     filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ff5656", endColorstr="#7f0000");  
  105.     background: -o-linear-gradient(top,#ff5656,7f0000);  
  106.     background-color#ff5656;  
  107. }  
  108. .customTable tr:first-child td:first-child  
  109. {  
  110.     border-width0px 0px 1px 0px;  
  111. }  
  112. .customTable tr:first-child td:last-child  
  113. {  
  114.     border-width0px 0px 1px 1px;  
  115. }  
Try to run the application on Google Chrome. After the view is rendered press F12 and go to the Network tab and again refresh the browser's page. You'll see the following snapshot.

Network tab

What we can observe is that for every CSS or a script file referenced on the view a call is made from the browser to the server for downloading it from the server to the browser. Also you could get the total number of bytes that were transferred from the browser to the server and vice versa for doing the preceding activity. In our case the number of CSS and script files were less but in a real-life scenario it would be more.

NOTE: After the page is cached in the user's browser the total number of bytes sent and received between the server and browser would be reduced. But for the initial request like in our case it would tend to increase the bandwidth on the server.

Now let's try to implement the Bundling feature. For this we've updated the index.cshtml, the update is for removing all the CSS links and script links from the view and wrapping those inside the BundleConfig.cs file. Please ensure you have removed all the CSS and script links from the index.cshtml view. Open your _Layout.cshtml file you'll find a link in the header section of the view by using the following code snippet:
  1. @Styles.Render("~/Content/css")  
“~/Content/css” is the virtual path given to the StyleBundle class inside the BundleConfig.cs file under your App_Start folder. The BundleConfig.cs file is the file that is used for doing the bundling operation in MVC4. You can get this file inside your app_start folder.

The following is the default code snippet for the BundleConfig.cs file. It has a single function with the name RegisterBundles.
  1. public class BundleConfig  
  2. {  
  3.     // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725  
  4.     public static void RegisterBundles(BundleCollection bundles)  
  5.     {  
  6.         bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  7.                     "~/Scripts/jquery-{version}.js"));  
  8.   
  9.         bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
  10.                     "~/Scripts/jquery-ui-{version}.js"));  

  11.         bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  12.                     "~/Scripts/jquery.unobtrusive*",  
  13.                     "~/Scripts/jquery.validate*"));  
  14.   
  15.         // Use the development version of Modernizr to develop with and learn from. Then, when you're  
  16.         // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
  17.         bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
  18.                     "~/Scripts/modernizr-*"));  
  19.   
  20.         bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));  
  21.   
  22.         bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(  
  23.                     "~/Content/themes/base/jquery.ui.core.css",  
  24.                     "~/Content/themes/base/jquery.ui.resizable.css",  
  25.                     "~/Content/themes/base/jquery.ui.selectable.css",  
  26.                     "~/Content/themes/base/jquery.ui.accordion.css",  
  27.                     "~/Content/themes/base/jquery.ui.autocomplete.css",  
  28.                     "~/Content/themes/base/jquery.ui.button.css",  
  29.                     "~/Content/themes/base/jquery.ui.dialog.css",  
  30.                     "~/Content/themes/base/jquery.ui.slider.css",  
  31.                     "~/Content/themes/base/jquery.ui.tabs.css",  
  32.                     "~/Content/themes/base/jquery.ui.datepicker.css",  
  33.                     "~/Content/themes/base/jquery.ui.progressbar.css",  
  34.                     "~/Content/themes/base/jquery.ui.theme.css"));  
  35.     }  
  36. }  
From looking at the code we can say that “~/Content/css” is the virtual path and it points to “~/Content/site.css”, in other words a specific file. Now we need to add a new entry for the “MyStyle.css” because our index.cshtml view is using the style inside that stylesheet. To do this there are two possible approaches: 
  1. You point the virtual path “~/content/css” to all the CSS files within the Content folder.
  2. You add a new entry in the BundleConfig file with a new virtual path pointing to the MyStyle.css file.

NOTE: “Virtual Path” are user-specific like how we name our classes and variables.

The problem with the first approach is that if your stylesheets follow a specific ordering then this way shouldn't be used. It will be better that you prefer to use the second approach because the first will not take care of ordering of the stylesheets it will randomly arrange the stylesheet and send it to the user's browser that may cause an undesired look and feel on the user's browser view.

Please comment all the code within the BundleConfig.RegisterBundles method. Do not comment the function signature. Now we'll try to update the RegisterBundles method. the following is the updated code snippet.

  1. public class BundleConfig  
  2. {  
  3.     // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725  
  4.     public static void RegisterBundles(BundleCollection bundles)  
  5.     {  
  6.         //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  7.         //            "~/Scripts/jquery-{version}.js"));  
  8.  
  9.         //bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
  10.         //            "~/Scripts/jquery-ui-{version}.js"));  
  11.   
  12.         //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  13.         //            "~/Scripts/jquery.unobtrusive*",  
  14.         //            "~/Scripts/jquery.validate*"));  
  15.   
  16.         //// Use the development version of Modernizr to develop with and learn from. Then, when you're  
  17.         //// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
  18.         //bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
  19.         //            "~/Scripts/modernizr-*"));  
  20.   
  21.         //bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));  
  22.   
  23.         //bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(  
  24.         //            "~/Content/themes/base/jquery.ui.core.css",  
  25.         //            "~/Content/themes/base/jquery.ui.resizable.css",  
  26.         //            "~/Content/themes/base/jquery.ui.selectable.css",  
  27.         //            "~/Content/themes/base/jquery.ui.accordion.css",  
  28.         //            "~/Content/themes/base/jquery.ui.autocomplete.css",  
  29.         //            "~/Content/themes/base/jquery.ui.button.css",  
  30.         //            "~/Content/themes/base/jquery.ui.dialog.css",  
  31.         //            "~/Content/themes/base/jquery.ui.slider.css",  
  32.         //            "~/Content/themes/base/jquery.ui.tabs.css",  
  33.         //            "~/Content/themes/base/jquery.ui.datepicker.css",  
  34.         //            "~/Content/themes/base/jquery.ui.progressbar.css",  
  35.         //            "~/Content/themes/base/jquery.ui.theme.css"));  
  36.   
  37.         //this will point to all the css files within the Content folder. But will not take of the ordering of stylesheets.  
  38.       bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));  
  39.   
  40.         bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  41.             "~/Scripts/jquery-{version}.js",  
  42.             "~/Scripts/jquery.unobtrusive*",  
  43.             "~/Scripts/jquery.validate*",  
  44.             "~/Scripts/modernizr-*"  
  45.             ));  
  46.     }  
NOTE 
  1. In the StyleBundle class we provided the virtual path the same, because we are referring to the same name inside the _Layout.cshtml file. But we have updated the Include function earlier it was pointing to a single file. Now it's pointing to all the CSS files within the Content folder. But as we said it will not take care of ordering of the CSS. So where the ordering of the CSS is important over there we shouldn't be using this approach. We should add a separate stylesheet entry as per the ordering required like in the case of script files how we did.
  2. In the case of the jquery-version.js file, at runtime the –version value will be updated with the version of jQuery file that resides inside your application. Also to take either the .js or .min.js file will take care of by reading the web.config file. The compilation element from the web.config file, if its debug attribute is set to “true” it will load the .js file and if it is set to “false” it will load the .min.js file. You can manually also force the MVC to load the minified version by setting the BundleTable.EnableOptimizations = true; inside your RegisterBundle Method.
  3. From the code we can also observe that for adding a stylesheet entry in the bundleconfig we make use of the StyleBundle Class and for adding an entry for JavaScript or jQuery files we make use of the ScriptBundle class.
  4. Inside the _Layout.cshtml file the @Style.Render(virtual path) method is used for rendering the stylesheets from the BundleConfig.cs file and the @Script.Render(vritual path) method is used for rendering the script from the BundleConfig.cs file.
  5. Also we need to comment the @Script.Render(~/bundles/modernizr) call within the head section of the _Layout.cshtml, because here we have commented the modernizr script in the BundleConfig.cs file.
  6. Your virtual path shouldn't be an actual path on the server.

Apart from these common script and CSS files, your view might be referring to some view specific script files. Let's use the example that we want our view to display the current date and time. For this we've created a new folder with the name “Home” inside the Script folder within the application and also added a new script file with the view name, in other words index.js. The following is the code snippet for it.

Index.js

  1. function GetCurrentDateAndTime() {  
  2.     var d = new Date();  
  3.     $("#myDiv").html("<b>Current Data And Time: " + d.toString() + "</b>");  
  4.     setInterval(GetCurrentDateAndTime, 1000);  
  5. }  
  6.   
  7. $(document).ready(function () {  
  8.     GetCurrentDateAndTime();  
  9. });  
Now how do we add this script to the view? Because if we add it to the BundleConfig.cs file then it would be unnecessarily downloaded to the user's browser even though the user is not browsing the index.cshtml file. So for view-specific script files we need to add it to that specific view only. If you carefully look at the _Layout.cshtml file it provides a provision for it by creating an optional section within it. Here is the code snippet that you can find in your _Layout.cshtml file.
  1. @RenderSection("scripts", required: false)  
We can make use of this section within those specific views where we need to add the view specific script files. Since the section is optional, on those views where there are no view-specific script files you can omit this section.

Let's update the index.cshtml to add this section. The following is the line of code that is before or after the H2 index element.
  1. @section scripts  
  2. {  
  3.     <script type="text/javascript" src="~/Scripts/Home/Index.js"></script>  
  4. }  
NOTE: Ensure that if your view specific script files make use of some other script files or if they have a dependency on some other script files then in that case those script files should be rendered first before your dependent script files are rendered. This could be handled in the _Layout.cshtml file by shifting the optional script section below the @Scripts.Render(virtual path) method.

Now let's try to run the application and see the changes in the network profiling.

network profiling

If you maximize the preceding image you'll find that the total number of bytes sent by the browser to the server and vice versa will be less as compared to the preceding screen shot. Also our index.js file is rendered after all the script files are rendered.

Now let's try to set the debug attribute to “false” and then check the changes.

set the debug attribute

You'll find that the total number of calls between the browser and server is more reduced now and there is a single entry for the CSS as well as for the script file where their names are encrypted. These files basically contain data from multiple CSS or script files merged into one and downloaded to the user's browser.

Our final output with Date and Time will be something. For this I've updated the index.cshtml file. You can get a copy by downloading it.

 

updated the index cshtml

Up Next
    Ebook Download
    View all
    Learn
    View all