In this chapter, we will cover the following recipes:
Downloading jQuery from jQuery.com
Understanding CDN for jQuery
Using the NuGet Package Manager to download jQuery
Adding jQuery to an empty ASP.NET web project using a script block
Adding jQuery to an empty ASP.NET web project using the ScriptManager control
Adding jQuery to an ASP.NET Master Page
Adding jQuery programmatically to a web form
Understanding the jQuery reference in the default Web Application template
Hello World in a web project using jQuery
Bundling jQuery in ASP.NET MVC
Using a CDN to load jQuery in MVC
Hello World in ASP.NET MVC using jQuery
Debugging jQuery code in Visual Studio
As a web developer, you often require to include functionalities in your websites that make writing a client script in JavaScript inevitable. Getting the client script to produce the same response for all browsers has always been a challenge. jQuery helps you overcome this difficulty. In essence, jQuery is a powerful JavaScript library that works across all browsers, such as Internet Explorer (IE), Firefox, Safari, Chrome, Opera, iOS, and Android. It takes away the agony that developers face in order to maintain their client scripts across different platforms.
jQuery is popular not only because of its cross-browser support, but also because it is packed with features that developers can plug and play. It has changed the way developers write a client script. In addition to reducing the amount of code that needs to be written, it provides features for traversing the DOM, event handling, building animations, and AJAX, among many more.
This chapter deals with acquiring the library and other supporting files. It aims to cover different aspects of including and using jQuery in ASP.NET 4.6 web application projects, such as web forms and MVCs.
Note
This book is based on Visual Studio 2015 and jQuery 2.1.4. The scripts have been tested in Internet Explorer 11.0.96, Mozilla Firefox 38.0.1, and Google Chrome 47.0.2526.
If you are familiar with downloading and including jQuery in your ASP.NET applications, you can skip this chapter and move on to recipes for manipulating controls in Chapter 2, Using jQuery Selectors with ASP.NET Controls.
This recipe explains how to download jQuery on your system along with the version/build to use and the supporting files that are required.
Following are the steps to download jQuery:
Launch any web browser and enter the URL http://www.jquery.com to access the jQuery home page:
Click on the Download jQuery button (highlighted in the preceding screenshot) on the right-hand side of the page. This opens up the download page with a list of available files, as shown in the following screenshot:
jQuery is available in two different major versions at the time of writing:
Version 1.x
Version 2.x
Though the Application Programming Interface (API) is the same for both major versions, the difference lies in the support offered for certain browsers. The 2.x line does not support old browsers, such as IE 6, 7, and 8, while the 1.x line continues with this support. So, if the end users of your application will not be using old browsers, you can download the 2.x version.
The jQuery library consists of a single JavaScript (.js
) file and can be downloaded in the following formats:
To download the file, simply right-click on the required version, 1.x or 2.x, and the required format: uncompressed or compressed. Save the file in a location of your choice as shown in the following screenshot:
Note the following naming convention for the jQuery library:
Uncompressed |
Compressed | |
---|---|---|
Version 1.x |
jquery-1.x.x.js |
jquery-1.x.x.min.js |
Version 2.x |
jquery-2.x.x.js |
jquery-2.x.x.min.js |
The compressed (minified) version is clearly distinct from the uncompressed version because of the .min.js
extension. The minified file uses code optimization techniques, such as removing whitespaces and comments as well as reducing variable names to one character. This version is difficult to read, so the uncompressed version is preferred when debugging.
On the download page, there is also a map file available with the .min.map
extension. Sometimes, when bugs appear in the production environment necessitating troubleshooting, the use of the minified file for debugging can be difficult. The map file simplifies this process. It maps the compressed file back to its unbuilt state so that during debugging, the experience becomes similar to using the uncompressed version.
A Content Delivery Network (CDN) hosts content for users through large distributed systems. The advantage of using a CDN is to improve the performance. When using a CDN to retrieve the jQuery library, if the files have been downloaded earlier, they will not be re-downloaded. This can help you improve the response time.
The following CDNs are available for jQuery files:
jQuery's CDN provided by MaxCDN
The Google CDN
The Microsoft CDN
The CDNJS CDN
The jsDelivr CDN
To include jQuery on a web page, the URL of the respective CDN can be used so that files can be directly served from the CDN instead of using the local copies. The following table summarizes the respective CDN URLs for jQuery files:
CDN |
URL |
---|---|
jQuery's CDN |
|
The Google CDN |
|
The Microsoft CDN |
|
The CDNJS CDN |
|
The jsDelivr CDN |
|
CDNs consist of servers situated in data centers in strategic locations across the globe. When a client requests a resource from a CDN, the server that is geographically closest to the client processes the request. These servers are also known as edge servers. In addition to this, edge servers have a caching mechanism to serve various assets. All this helps you improve the client's response time.
NuGet is a package manager available with Visual Studio. It simplifies the process of installing and upgrading packages. This recipe demonstrates the use of NuGet to download the jQuery library.
To launch NuGet for a particular project, go to Tools | NuGet Package Manager | Manage NuGet Packages for Solution... as shown in the following screenshot:
Alternatively, right-click on the project in the Solution Explorer tab, and select Manage NuGet Packages.
Perform the following steps to download jQuery using NuGet Manager:
In the NuGet Package Manager, as shown in the following screenshot, select the jQuery package from the left-hand side panel. In the right-hand side panel, select the Version that you would like to use in your web project from the drop-down menu. Click on the Install button:
Click on OK when prompted for confirmation in order to make the required changes to the solution.
The NuGet Package Manager downloads the selected version of jQuery in the Scripts folder. Any other version existing in the Scripts folder is deleted. The Scripts folder will look like the following screenshot:
The files downloaded by NuGet are as follows (the version numbers may change in the future):
The Intellisense file: jquery-2.1.4.intellisense.js
The debug version : jquery-2.1.4.js
The release version: jquery-2.1.4.min.js
The map file: jquery-2.1.4.min.map
To create ASP.NET 4 .6 Web Applications, Visual Studio provides various ready templates such as Empty, Web Forms, MVC, Web API, and so on. This recipe will use the Empty template, which provides the developer with an empty project structure that consists of only the web.config
file.
Tip
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Following are the steps to create a project by using Empty template:
Create a new project in Visual Studio by going to File | New | Project..., as shown in the following screenshot:
Tip
Website or web project?
Instead of creating a new project, you can also create a new website. Unlike a project, a website does not contain a collective project file to track individual files in the application. To create a website, go to File | New | Web Site.... This will launch the New Website dialog box with the list of available templates. Select the ASP.NET Empty WebSite template.
This will launch the New Project dialog box, as shown in the following screenshot. From the left-hand side panel, select your desired programming language, Visual C# or Visual Basic, and then, select ASP.NET Web Application from the middle panel:
Enter
WebApplication1
(or any suitable name) in the Name field. Click on the Browse button to go to the desired Location where you would like to save the application. Click on OK.This will launch the Select a template dialog box, as shown in the following screenshot:
From ASP.NET 4.6 Templates, select Empty, and click on OK. Visual Studio will create an empty project in the Solution Explorer tab, as shown in the following screenshot:
Following are the steps to include jQuery using script block:
JavaScript files are usually placed in a folder named Scripts in the web application. So, in the Solution Explorer tab, right-click on the project and go to Add | New Folder from the menu:
Rename the folder to
Scripts
. Now, right-click on the Scripts folder, and go to Add | Existing Item... as shown in the following screenshot:Now, browse to the location where you have saved the downloaded copy of the jQuery files (refer to the Downloading jQuery from jQuery.com recipe), and click on OK. It is recommended that you add both the uncompressed and compressed versions. The Scripts folder will be updated, as shown in the following screenshot:
Next, create a new web form in the project by right-clicking on the project and navigating to Add | New Item.... From the dialog box, select Web Form, and enter a suitable name for the web form, such as
Default.aspx
:To use jQuery on the web form, simply drag and drop the required jQuery file, that is, uncompressed or compressed on the web form. Or alternatively, include the following
<script>
tag in the<head>
element:For development mode, the code is as follows:
<script src="Scripts/jquery-2.1.4.js"></script>
For release mode, the code is as follows:
<script src="Scripts/jquery-2.1.4.min.js"></script>
Adding jQuery to a web form using the script block has some disadvantages. If the application is upgraded to use the latest version of jQuery, all the web forms with the <script>
tag require to be changed. Secondly, switching from the uncompressed version in the development environment to the compressed version in the release environment should be handled manually and is hence error-prone. Using the ASP.NET ScriptManager
control helps you overcome this problem. It can also load jQuery directly from CDN instead of using the local copy.
Create a new ASP.NET Web Application project using the Empty template by following the steps listed in the Adding jQuery to an empty ASP.NET web project using a script block recipe. Name the project
WebApplication2
(or any other suitable name).Follow the steps in the preceding recipe to add the jQuery library (the uncompressed and compressed formats) to the Scripts folder.
Follow the steps to add a new web form to the project.
Following are the steps to add jQuery to ASP.NET web project using the ScriptManager
control:
Open the web form in the Design mode.
Launch the Toolbox. This can be done in two ways. From the File menu at the top of the page, go to View | Toolbox. Alternatively, use the shortcut keys, Ctrl + Alt + X.
Go to Toolbox | AJAX Extensions, and drag and drop the ScriptManager control onto the form:
Right-click on the project in the Solution Explorer tab, and go to Add | New Item.... From the dialog box, select Global Application Class. This will add the Global.asax file to the project:
Open the
Global.asax
file and include the following namespace at the top of the page:For VB, the code is as follows:
Imports System.Web.UI
For C#, the code is as follows:
using System.Web.UI;
In the
Application_Start
event in theGlobal.asax
file, add the following code to create a script that maps to jQuery:For VB, the code is as follows:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ScriptManager.ScriptResourceMapping.AddDefinition("jquery", New ScriptResourceDefinition() With { .Path = "~/Scripts/jquery-2.1.4.min.js", .DebugPath = "~/Scripts/jquery-2.1.4.js", .CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", .CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", .CdnSupportsSecureConnection = True, .LoadSuccessExpression = "window.jQuery"}) End Sub
For C#, the code is as follows:
protected void Application_Start(object sender, EventArgs e) { ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-2.1.4.min.js", DebugPath = "~/Scripts/jquery-2.1.4.js", CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" }); }
Open the
Default.aspx
web form in the Source mode. Add the followingScriptReference
to theScriptManager
control:<asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Name="jquery" /> </Scripts> </asp:ScriptManager>
Note
When using the
ScriptManager
control to add a reference to the jQuery library, the jQuery code should be placed after theScriptManager
control, that is, after the jQuery reference has been declared; otherwise, the page will throw an error. It is also important to note that theScriptManager
control should reside inside the<form>
element.To retrieve the jQuery files from CDN, set the
EnableCdn
property of theScriptManager
control totrue
, as follows:<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true"> <Scripts> <asp:ScriptReference Name="jquery" /> </Scripts> </asp:ScriptManager>
This is how the ScriptManager control works:
The
ScriptManager
control can be used to load JavaScript files, such as the jQuery library. This can be done by adding theScriptReference
to jQuery in theScriptManager
control, as follows:<asp:ScriptReference Name="jquery" />
However, we require to define this mapping. This can be done in the
Global.asax
file using aScriptResourceDefinition
object, which exposes the following properties:The
ScriptResourceDefinition
object defined inGlobal.asax
is namedjquery
. TheScriptManager
control uses the same name to load the reference on the web form.In the development/debug mode, the script is served from
DebugPath
while in the release mode, it is served fromPath
.Tip
Running in development/debug and release modes
To run the application in the development/debug mode, set the
debug
attribute of the<compilation>
element in theweb.config
totrue
as follows:<system.web> <compilation debug="true"/> ….. </system.web>
When the
debug
attribute is set tofalse
, the application will run in the release mode.If
EnableCdn
is set totrue
, the script is served from the CDN path, that is, fromCdnDebugPath
in the development/debug mode andCdnPath
in the release mode.The
LoadSuccessExpression
property renders an inline script to load the library from the local path in the event of a CDN failure. By right-clicking on the web page and viewing the source, note that theScriptManager
control adds a fall back mechanism when the CDN is unavailable and files are served locally instead:
Master Pages are used to achieve a uniform look and feel in the website. They maintain a consistent layout across all the content pages. Including jQuery in the Master Page ensures that all the content pages using that Master Page will also have the library included by default. This recipe will demonstrate how this can be done.
Note
A Master Page is an ASP.NET file with the .Master
extension. It has a @Master
directive at the top of the layout instead of the @Page
directive in an ordinary .aspx
page.
Create a new ASP.NET Web Application project using the Empty template by following the steps listed in the Adding jQuery to an empty ASP.NET web project using a script block recipe. Name the project
WebApplicationWithMaster
(or any other suitable name).Follow the steps in the previous recipe to add the jQuery library (the uncompressed and compressed formats) to the Scripts folder.
In the Solution Explorer tab, right-click on the project, and go to Add | New Item.... This will launch a dialog box, as shown in the following screenshot. From the dialog box, select Web Forms Master Page. Name the Master Page
Default.Master
, and click on Add:To add a web form—that is, a content page—to the project, right-click on the project in the Solution Explorer tab again, and navigate to Add | New Item.... From the dialog box, this time select Web Form with Master Page, as shown in the following screenshot. Name the web form
Default.aspx
, and click on Add:This will launch a dialog box so that you can select the Master Page. From the dialog box, as shown in the following screenshot, select the Master Page to be associated with the content page, and click on OK:
To incorporate jQuery in an ASP.NET Master Page, follow these steps:
Open the
Default.Master
Master Page in the Source mode, and add a reference to the jQuery library using either the<script>
block (refer to the Adding jQuery to an empty ASP.NET web project using a script block recipe) or theScriptManager
control (refer to the Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe), as shown in the following screenshot:Note
When using the
<script>
block, thejQuery
reference should preferably be placed in the<head>
element.When using the
ScriptManager
control, the control should preferably be placed in the<form>
element before theContentPlaceHolder
in which the jQuery code will be added later to the content pages. TheGlobal.asax
file should also be updated in order to add the requiredScriptResourceDefinition
, as described in the Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe.The required jQuery code can now be added to the
ContentPlaceHolder
(withID = "ContentPlaceHolder1"
) in theDefault.aspx
web form.
On running the application, when the Default.aspx
content page is loaded, the HTML markup from the Master page adds the reference to the jQuery library. This makes the content page jQuery-ready so that any jQuery code can be executed.
To check whether the jQuery reference has been added to the page, run the project and launch Default.aspx
in the browser. Right-click on the page in the browser window and select View Source. The jQuery reference will be seen on the page, as shown in the following screenshot:
In addition to adding jQuery to web forms using the script block and the ScriptManager
control, the code-behind file can also emit the required script code. This recipe will demonstrate how this can be done.
Create an ASP.NET Web Application project by navigating to File | New | Project | ASP.NET Web Application. Select the Empty template. Name the project
WebApplicationWithPageLoad
(or any other suitable name).Add a new Web Form to the project and name it
Default.aspx
.Add the jQuery library files to the Scripts folder.
From the Solution Explorer tab, navigate to Default.aspx.vb (VB) or Default.aspx.cs (C#), which is the code-behind file for the web form. Open this file.
In the Page_Load
event handler of Default.aspx.vb
, use the RegisterClientScriptInclude
method to generate a script block on the page, as follows:
For VB, the code is as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Page.ClientScript.RegisterClientScriptInclude("jquery", Page.ResolveUrl("~/Scripts/jquery-2.1.4.js")) End Sub
For C#, the code is as follows:
protected void Page_Load(object sender, EventArgs e) { Page.ClientScript.RegisterClientScriptInclude("jquery", Page.ResolveUrl("~/Scripts/jquery-2.1.4.js")); }
The RegisterClientScriptInclude
method requires two parameters: the key and URL. It adds the script block with the path to the jQuery library in the <form>
element, as shown in the following screenshot. The Page.ResolveUrl
method is used to return a URL relative to the site root:
Since the jQuery library is added to the <form>
element, all the jQuery code should be written in the <form>
element instead of the <head>
element, preferably toward the end of the page before closing the <form>
element.
So far, all examples have used the Empty template for the ASP.NET Web Application project. When using a non-empty built-in web application template, ASP.NET adds a reference to the jQuery library in the Master Page using the ScriptManager
control. This recipe walks you through the important details of this mapping.
Here are the steps to create an ASP.NET web application using the default web application template:
Create a new project by navigating to File | New | Project.... From the dialog box, select ASP.NET Web Application. Name the project
DemoWebApplication
(or any other suitable name), and click on OK.A new dialog box will be launched. Select Web Forms from the available templates. Note that the Web Forms checkbox is checked by selecting the Web Forms template (refer to the following screenshot) and click on OK as shown in the following screenshot:
Open the
Site.Master
Master Page in the Source mode, as shown in the following screenshot:Notice that the
ScriptManager
control that is added to the<form>
element has the following reference to jQuery:<asp:ScriptReference Name="jquery" />
When you follow the preceding steps, this is how the web application is mapped to the jQuery library:
The
ScriptManager
control switches the jQuery library between the development and release versions, depending on thedebug
attribute of the<compilation>
element inweb.config
:<compilation debug="true"/>
When the
debug
attribute istrue
, the uncompressed version is used. Whendebug
isfalse
, the minified version is used.The default template is shipped with the
AspNet.ScriptManager.jQuery
package. This package adds the followingScriptMappings
to jQuery in thePreApplicationStart
method of the application as follows:For C#, the code is as follows:
string str = "2.4.1"; ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-" + str + ".min.js", DebugPath = "~/Scripts/jquery-" + str + ".js", CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".min.js", CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + str + ".js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" });
When the
EnableCdn
property of theScriptManager
control is set totrue
,CdnPath
andCdnDebugPath
are used in release and development modes, respectively, to serve scripts from the Microsoft CDN:<asp:ScriptManager runat="server" EnableCdn="true">
However, if the CDN is down or if the application is offline, the
ScriptManager
control will include a fallback mechanism to serve the local copy of jQuery, as shown in the following screenshot:To change the CDN to another, for example Google CDN, we need to change
ScriptResourceMapping
in theRegisterBundles
method inBundleConfig
, as shown in the following code. This module/class is located in theApp_Start
folder:For VB, the code is as follows:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", New ScriptResourceDefinition() With { .Path = "~/Scripts/jquery-2.1.4.min.js", .DebugPath = "~/Scripts/jquery-2.1.4.js", .CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", .CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", .CdnSupportsSecureConnection = True, .LoadSuccessExpression = "window.jQuery"})
For C#, the code is as follows:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition { Path = "~/Scripts/jquery-2.1.4.min.js", DebugPath = "~/Scripts/jquery-2.1.4.js", CdnPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js", CdnDebugPath = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js", CdnSupportsSecureConnection = true, LoadSuccessExpression = "window.jQuery" });
By running the page and viewing the source in the browser window, note that Microsoft CDN is replaced with Google CDN as required:
Open the
Global.asax
page to view the registration of bundles in theApplication_Start
event handler as follows:For VB, the code is as follows:
BundleConfig.RegisterBundles(BundleTable.Bundles)
For C#, the code is as follows:
BundleConfig.RegisterBundles(BundleTable.Bundles);
Until now, all recipes have demonstrated different ways to add the jQuery library to web pages. This is the first step in making the page jQuery-ready. In this recipe, let's move on to the next step: writing the jQuery code inside a script block to manipulate controls in a web form. We will display a simple Hello World message on the web page by manipulating a Label
control on a web form.
Create a Web Application project by going to File | New | Project | ASP.NET Web Application. Select the Empty template. Name the project
HelloWorld
(or any other suitable name).Add a new Web Form to the project.
Add the jQuery library files to the Scripts folder.
Add a reference to the jQuery library on the web form using any method of your choice.
Open the web form in the Design mode and drag and drop a Label control by navigating to the Toolbox | Standard controls. Change the properties of the
Label
control as follows:<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
If a jQuery reference is added to the <head>
element, then include the following <script>
block in the <head>
element. Otherwise, include the <form>
element, preferably before the <form>
tag is closed:
<script type="text/javascript"> $(document).ready(function () { var fontStyle = "Arial"; var fontSize = 28; $("#<%=lblMessage.ClientID%>").css("font-family", fontStyle); $("#<%=lblMessage.ClientID%>").css("font-size", fontSize); $("#<%=lblMessage.ClientID%>").text("Hello World!!"); }); </script>
Following are the steps to print Hello World!! in a web project using jQuery:
In the preceding jQuery code, the
$
symbol is used to instantiate thejQuery
object.The
.ready()
function is triggered when the DOM is ready. It is commonly used to execute the required jQuery code on the page.The
Label
control can be accessed from the jQuery code using ASP.NET'sClientID
property and jQuery's#identifier
selector.Using the
.css()
property of thejQuery
object, the font style, size, and text of theLabel
control are manipulated so that the following output is displayed on running the application:
Model View Controller (MVC) is a design pattern that separates design (Model), presentation (View), and action (Controller). Because of its popularity with developers, Visual Studio provides ready templates that are used to create MVC projects.
Similar to web forms, jQuery can be included in MVC views using the <script>
tag. In this example, however, let's take a look at the use of bundling for this purpose.
Bundling helps you reduce the number of HTTP requests made by the browser. It is a feature that allows style sheets, JavaScript, or other files to be combined together in a single file called a bundle. This combined file can be downloaded as one unit using a single HTTP request.
Launch a new ASP.NET Web Application project in Visual Studio using the Empty template. Ensure that the MVC checkbox is checked, as shown in the following screenshot:
This will create a project with MVC folders. Right-click on the Controllers folder in the Solution Explorer tab, and go to Add | Controller... as shown in the following screenshot:
This will launch the Add Scaffold dialog box. Select MVC 5 Controller – Empty, and click on the Add button:
On being prompted to add a name for the controller, type
HomeController
and click on the Add button:Next, open the HomeController in the source mode, and right-click on the
Index
action method, as shown in the following screenshot. Click on Add View... as shown in the following screenshot:This will launch the Add View dialog box. From the Template field, select Empty (without model). Uncheck the Use a layout page option and click the Add button to continue:
To use bundling, we need to install the ASP.NET Web Optimization package. This can be done from NuGet. From the
File
menu, launch NuGet by navigating to Project | Manage NuGet Packages. Select Microsoft.AspNet.Web.Optimization from the list of available packages. If the package is not visible, search forweb.optimization
, as shown in the following screenshot. Click on the Install button to download and install the latest version:Lastly, create a
Scripts
folder in the project and include the jQuery library files in the folder.
Follow these steps to bundle jQuery in ASP.NET MVC:
Open the
BundleConfig
class in theApp_Start
folder in the MVC project. If the file does not exist, create a newmodule
(VB)/class
(C#) in theApp_Start
folder, and name itBundleConfig.vb
/BundleConfig.cs
.In
BundleConfig.vb
/BundleConfig.cs
, add a namespace toSystem.Web.Optimization
at the top of the file:For VB, the code is as follows:
Imports System.Web.Optimization
For C#, the code is as follows:
using System.Web.Optimization;
Register and configure a bundle for jQuery in the
RegisterBundles
method inBundleConfig
as follows:For VB, the code is as follows:
Public Module BundleConfig Public Sub RegisterBundles(ByVal bundles As BundleCollection) bundles.Add(New ScriptBundle("~/Scripts/jquery").Include( "~/Scripts/jquery-{version}.js")) End Sub End Module
For C#, the code is as follows:
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/Scripts/jquery").Include( "~/Scripts/jquery-{version}.js")); } }
To enable bundling in the development mode (optional), add the following code to the
RegisterBundles
method:For VB, the code is as follows:
BundleTable.EnableOptimizations = True
For C#, the code is as follows:
BundleTable.EnableOptimizations = true;
In the
Global.asax file
, include the namespace forSystem.Web.Optimization
, as shown in step 2 mentioned previously. Then, register the bundle in theApplication_Start
method as follows:For VB, the code is as follows:
BundleConfig.RegisterBundles(BundleTable.Bundles)
For C#, the code is as follows:
BundleConfig.RegisterBundles(BundleTable.Bundles);
Now, open the Index view and include the namespace for
System.Web.Optimization
, as shown in the following code:For VB, the code is as follows:
@Imports System.Web.Optimization
For C#, the code is as follows:
@using System.Web.Optimization
Next, add the script reference for jQuery to the view in the
<head>
element as follows:@Scripts.Render("~/Scripts/jquery")
Note
Bundling is disabled in the debug mode by setting the debug
attribute to true
in the <compilation>
element in the web.config
file. To override this setting and enable bundling in the debug mode, set the EnableOptimizations
property of the BundleTable
class to true
in the RegisterBundles
method.
Unless EnableOptimizations
is set to true
, or the debug
attribute is set to false
, the files will not be bundled and the debug versions of the files will be used instead of the minified versions.
Bundling jQuery in ASP.NET MVC can be done by following these steps:
The wildcard string used for bundling jQuery
~/Scripts/jquery-{version}.js
includes the development as well as the minified versions. The.vsdoc
file, which is used by IntelliSense, is not included in the bundle.When the debug mode is on, the corresponding debug version is used. In the release mode, the minified version is bundled.
On running the view in a browser, the bundled file can be seen on viewing the source in the browser window, as shown in the following HTML markup:
Because of the advantages of using CDN in web applications, bundling also supports the loading of files directly from CDN. This recipe will explain how a MVC project can be configured to use CDN.
This recipe is a continuation of the previous recipe, Bundling jQuery in ASP.NET MVC. So, follow all the steps described in the previous recipe.
Following are the steps to load jQuery in MVC:
In the
BundleConfig
module/class, modify theRegisterBundles
method in order to set theUseCdn
property totrue
, as shown in the code snippet in step 2.Declare the required CDN path, and add a
ScriptBundle
with two parameters: the virtual path of the bundle and the CDN path, as follows:For VB, the code is as follows:
Public Module BundleConfig Public Sub RegisterBundles(ByVal bundles As BundleCollection) bundles.UseCdn = True Dim cdnPath As String = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js" bundles.Add(New ScriptBundle("~/Scripts/jquery", cdnPath).Include("~/Scripts/jquery-{version}.js")) End Sub End Module
For C#, the code is as follows:
public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.UseCdn = true; string cdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"; bundles.Add(new ScriptBundle("~/Scripts/jquery", cdnPath).Include("~/Scripts/jquery-{version}.js")); } }
Following are the steps to load jQuery in MVC using CDN:
By setting the
UseCdn
property, serving of bundled scripts from the CDN is enabled.In the development mode, the application retrieves files from the local Scripts folder. In the release mode, the CDN path is used to serve the bundled scripts.
However, there is a possibility that the CDN is down. Hence, a fallback mechanism is required so that the scripts are served locally in such a scenario. This can be done by adding the following
<script>
block in the required view:@Scripts.Render("~/Scripts/jquery") <script type="text/javascript"> if (typeof jQuery == 'undefined') { var e = document.createElement('script'); e.src = '@Url.Content("~/Scripts/jquery-2.4.1.js")'; e.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(e); } </script>
This recipe demonstrates how to write a simple jQuery code to display Hello World in the ASP.NET MVC project.
Following are the steps to write simple jQuery code:
Open the Index view, and add the following markup to the
<body>
element:<div id="divMessage"> </div>
In the
<head>
element, include the following jQuery code:<script type="text/javascript"> $(document).ready(function () { var fontStyle = "Arial"; var fontSize = 28; $("#divMessage").css("font-family", fontStyle); $("#divMessage").css("font-size", fontSize); $("#divMessage").text("Hello World!!"); }); </script>
Right-click on the Index view, and select View in Browser (Internet Explorer).
Following are the steps to print Hello World in ASP.NET MVC using jQuery:
The
$
symbol is used to instantiate thejQuery
object.The
.ready()
function is triggered when the DOM is ready. It is commonly used to execute the required jQuery code on the page.The HTML
<div>
element withid = "divMessage",
which is used to display the Hello World message, can be accessed using its ID with jQuery's#identifier
selector—that is, using the#divMessage
selector.Using the
.css()
property of thejQuery
object, the font style, size, and text of the<div>
element are manipulated so that the following output is displayed on running the application:
Debugging is inevitable for resolving bugs in the code during the development phase. Sometimes, bugs also slip into production. Visual Studio provides support for developers to debug the JavaScript code in the same manner as the server-side code. However, there is a limitation and debugging in Visual Studio can only be done using the Internet Explorer browser at present.
To enable debugging for a particular project, both the project properties and
web.config
must be updated. To update the project properties, right-click on the project in the Solution Explorer tab, and select Properties. Go to the Web tab, and select the ASP.NET checkbox in the Debuggers section, as shown in the following screenshot:In the
web.config
file, go to theconfiguration/system.web/compilation
element. If the element does not exist, add a new node. To enable debugging, thedebug
property of the<compilation>
node should be set totrue
, as follows:<compilation debug="true" … />
Debugging jQuery code in Visual Studio can be done by performing the following steps:
The first step in debugging is to define breakpoints in the JavaScript code, where the execution will be halted so that variables, program flow, and so on can be inspected. To define breakpoints, just click on the left-hand side gray margin in the source code. Each breakpoint is represented by a small red circle, as shown in the following figure:
Press F5, or navigate to Debug | Start Debugging, to start running the application in the debug mode. The execution will stop at the first breakpoint that it comes across, as shown in the following screenshot:
To launch the Watch window in order to observe the values of variables during runtime, go to Debug | Windows | Watch. This will display the window, as shown in the preceding screenshot.
You will also be able to see a window showing the breakpoints by navigating to Debug | Windows | Breakpoints. The result is shown in the following screenshot:
To trace the code line by line, press F11 or navigate to Debug | Step Into at each line. To skip to the next breakpoint, press F5.
Press Shift + F5 to stop debugging.
Note
Make sure that you turn off debugging before launching the application in the production environment. An application that has debugging enabled has a slower performance since debugging generates additional information to enable the debugger to display the contents of variables. It also outputs more information to the call stack, which can become a security issue in the production environment.