ScriptBundle in ASP.NET MVC

The goal of this tutorial is to implement the ScriptBundle in a ASP.NET MVC, using Microsoft Visual Studio. The purpose of Script Bundle is to reduce the resource (JavaScript, CSS, Bootstrap, or other libraries) downloading times.

In Visual Studio, first create a new Empty ASP.NET (C#) Web Application. After creating a new empty ASP.NET Web Application project, open the Nuget Console.

NuGet command – Download Web Optimization

Open the NuGet console and enter the following command:

Install-Package Microsoft.AspNet.Web.Optimization

Press the “Enter” or “Return” key to download the resource.

Creating a new file – BundleConfig.cs

After downloading the resource, under the App_Start folder create a new cs file called BundleConfig.cs

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

namespace CodeRepository.Web
{
	public class BundleConfig
	    {
	        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.validate*"));
	
	            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
	                        "~/Scripts/modernizr-*"));
	
	            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
	                      "~/Scripts/bootstrap.js",
	                      "~/Scripts/respond.js"));
	
	            bundles.Add(new StyleBundle("~/Content/css").Include(
	                      "~/Content/bootstrap.css",
	                      "~/Content/master.min.css"));
	        }
	    }
}

Modify Global.asax file

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

The source code should look like this:

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Add a namespace in Web.Config

Open web.config under the Views folder. Add the following snippet inside the namespaces tag:

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

Machine generated alternative text:
References 
App Data 
App_Start 
Content 
Controllers 
Models 
Scripts 
Views 
Home 
Index.cshtml 
Shared 
LayoutHome.cshtml 
u • u uaI.asaX 
packages.config 
Web.config 
7 
8 
9 
le 
11 
12 
13 
14 
15 
16 
17 
18 
19 
21 
22 
23 
24 
<section name="pages" Web . WebPages . Razor . Configu 
Culture-neutral, PublicKeyToken=31BF3856AD364E35" requirePer 
8 
8 
</sectionGroup> 
</configSections> 
< system . web . webPages . razor> 
<host Web .Mvc .MvcWebRazorHostFactory, 
<pages Web .Mvc . WebViewPage 
<namespaces> 
<add Web .Mvc 
<add Web .Mvc . Ajax" 
<add Web .Mvc . Html" / > 
<add Web . Routing" 
. razor> 
Syste 
<add namespace: 
</pages> 
< / system. web . webPages 
" System. Web . Optimxzatxon " / >
In the web.config, insert the namespace between the namespaces tag.

Creating a new controller

Create the a Controller called Home. Right-click the Controller and mouse over Add and click Controller.

Machine generated alternative text:
Controllers 
HomeControlli 
Models 
Scripts 
Views 
Home 
Shared 
LayoutH01 
ViewStart.csht 
o 
View in Browser (Firefox) 
Browse With... 
Cleanup Selected Code 
Collapse Recursively 
Add 
Scope to This 
Ctrl+Shift+W 
13 
14 
15 
16 
Controller... 
New Item... 
(Scripts . Render ( " N/bu 
Esc ripts . Render ( "N/bu 
</html> 
Ctrl+Shift+A
Right-click Controllers, click Add and then Controller.

In the Add New Scaffolded Item, select MVC 5 Controller – Empty and click the Add button.

Machine generated alternative text:
Add New Scaffolded Item 
Installed 
Common 
ontrolle 
MVC 5 Controller - Empty 
MVC 5 Controller with read/write actions 
MVC 5 Controller with views, using Entity Framework 
Web API 2 Controller — Empty 
Web API 2 Controller with actions, using Entity Framework 
Web API 2 Controller with read/write actions 
x 
MVC 5 Controller - Empty 
by Microsoft 
v5.o.o.o 
An empty MVC controller. 
Id: MvcControllerEmptyScaffolder 
Web API 2 OData v3 Controller with actions, using Entity Framework 
Web API 2 OData v3 Controller with read/write actions 
Click here to go online and find more scaffolding extensions. 
Add 
Cancel
Add MVC 5 Controller – Empty

The HomeController.cs has been added under the Controllers folder.

HomeController.cs was added inside the Controllers folder.

Under the Views folder, right-click the Shared folder and add a MVC 5 Layout Page (Razor) and call it _LayoutHome.

Adding a MVC 5 Layout Page (Razor) under the Shared folder.

In the _LayoutHome folder, add the following snippets:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</body>
</html>
The source code for _LayoutHome.cshtml

Right-click the Home folder and click MVC 5 View Page (Razor) page.

Right-click Home and add MVC 5 View Page (Razor).

The Item name is Index and press OK button.

Item name: Index

Open _VewStart.cshtml and add the following snippet that will display the controller’s masterpage (layout).

    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["CONTROLLER"].ToString();
    string cLayout = "";

    switch (controller.ToLower())
    {
        case "home":
            cLayout = "~/Views/Shared/_LayoutHome.cshtml";
            break;
        default:
            cLayout = "";
            break;
    }

    Layout = cLayout;
}

Run the program

Run the program. A web browser is opened. View the source of the page and you will see that the CSS and JavaScript were added: