Jquery Cookbook - Second Edition - Sample Chapter
Jquery Cookbook - Second Edition - Sample Chapter
ee
server controls
Get to know about event handling and
DOM traversal
ASP.NET jQuery Cookbook explores the wide range of utilities that the jQuery library provides. It teaches you
the nitty-gritty of plugging in these features in ASP.NET web applications. It covers every aspect of interfacing
with the library, right from downloading and including jQuery on web pages to selecting controls, handling
events, and creating animations. This book also walks you through DOM traversal and manipulation in
ASP.NET and then through visual effects and graphics in ASP.NET sites. It explores advanced features such as
posting Ajax requests and writing plugins. It will provide you with all the information you need to use this library
condently with ASP.NET.
Second Edition
jQuery is a lightweight JavaScript library that has changed the landscape of client scripting in web
applications. It has popularity with ASP.NET developers and is distributed with Visual Studio and the NuGet
package manager.
and animations
pl
e
Sa
and problems
problems efciently
real-world problems
Preface
jQuery is a lightweight JavaScript library that has changed the landscape of client scripting in
web applications. Developed by John Resig in 2006, it has taken the Web by storm because
of its cross-browser compatibility and its ability to get more done with less code. The library
is supported by an active community of developers and has grown significantly over the
years. Using jQuery eases many client scripting tasks, such as event handling, embedding
animations, writing Ajax enabled pages, among many more, and adds to the interactive
experience of the end user. Its extensible plugin architecture enables developers to build
additional functionalities on top of the core library.
Learning jQuery and using it in ASP.NET applications is an indispensable skill for ASP.NET
developers. This book attempts to impart this skill by exploring diverse recipes for fast and
easy solutions to some of the commonly encountered problems in ASP.NET 4.6 applications.
Preface
Chapter 4, DOM Traversal and Manipulation in ASP.NET, describes techniques to traverse the
document, such as accessing parent, child, or sibling elements. It also teaches manipulation
strategies to add and remove elements at runtime.
Chapter 5, Visual Effects in ASP.NET Sites, discusses recipes to create different types of
animation effects on ASP.NET controls, such as Panel, AdRotator, TreeView, Menu, and
GridView. Effects such as enlarging, sliding, and fading are covered in this chapter.
Chapter 6, Working with Graphics in ASP.NET Sites, discusses recipes to work with images
and explains effects, such as zooming, scrolling, and fading on images. Utilities such as
image gallery, image preview, and 5-star rating control are also explored in this chapter.
Chapter 7, Ajax Using jQuery, explains how Ajax calls can be made to page methods,
web services, WCF services, Web API, MVC controllers, and HTTP handlers.
Chapter 8, Creating and Using jQuery Plugins, demonstrates how plugins can be created
and included in projects. It also describes how to use the Node Package Manager (NPM)
and Bower to download and manage third-party plugins.
Chapter 9, Useful jQuery Recipes for ASP.NET Sites, summarizes the book with diverse
recipes to solve common real-world problems. You can find this chapter at: https://www.
packtpub.com/sites/default/files/downloads/4836OT_Chapter_09.
Adding jQuery to an empty ASP.NET web project using the ScriptManager control
Introduction
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.
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.
Getting ready
Following are the steps to download jQuery:
1. Launch any web browser and enter the URL http://www.jquery.com to access
the jQuery home page:
Chapter 1
2. 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:
How to do it
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:
Chapter 1
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.
See also
The Understanding CDN for jQuery recipe.
How to do it
The following CDNs are available for jQuery files:
URL
jQuery's CDN
Version 2.x:
http://code.jquery.com/jquery-2.x.x.js
http://code.jquery.com/jquery-2.x.x.min.js
Version 1.x:
http://code.jquery.com/jquery-1.x.x.js
http://code.jquery.com/jquery-1.x.x.min.js
Version 2.x:
https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/
jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/2.x.x/
jquery.min.js
Version 1.x:
https://ajax.googleapis.com/ajax/libs/jquery/1.x.x/
jquery.js
https://ajax.googleapis.com/ajax/libs/jquery/1.x.x/
jquery.min.js
The Microsoft
CDN
Version 2.x:
http://ajax.aspnetcdn.com/ajax/jQuery/jquery2.x.x.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery2.x.x.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery2.x.x.min.map
Version 1.x:
http://ajax.aspnetcdn.com/ajax/jQuery/jquery1.x.x.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery1.x.x.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery1.x.x.min.map
Chapter 1
CDN
URL
Version 2.x:
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/
jquery.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/
jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.x.x/
jquery.min.map
Version 1.x:
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/
jquery.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/
jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery/1.x.x/
jquery.min.map
Version 2.x:
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.js
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.js
https://cdn.jsdelivr.net/jquery/2.x.x/jquery.min.map
Version 1.x:
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.js
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.js
https://cdn.jsdelivr.net/jquery/1.x.x/jquery.min.map
How it works
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.
7
See also
The Using NuGet Package Manager to download jQuery recipe
Getting ready
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.
8
Chapter 1
How to do it
Perform the following steps to download jQuery using NuGet Manager:
1. 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:
2. Click on OK when prompted for confirmation in order to make the required changes to
the solution.
How it works
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):
See also
The Downloading jQuery from jQuery.com recipe
Chapter 1
Getting ready
Following are the steps to create a project by using Empty template:
1. Create a new project in Visual Studio by going to File | New | Project..., as shown in
the following screenshot:
11
3. 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.
4. This will launch the Select a template dialog box, as shown in the
following screenshot:
12
Chapter 1
5. 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:
13
How to do it
Following are the steps to include jQuery using script block:
1. 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:
2. Rename the folder to Scripts. Now, right-click on the Scripts folder, and go to
Add | Existing Item... as shown in the following screenshot:
14
Chapter 1
3. 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:
15
5. 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>
16
Chapter 1
See also
The Downloading jQuery from jQuery.com recipe
Getting ready
1. 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).
2. Follow the steps in the preceding recipe to add the jQuery library (the uncompressed
and compressed formats) to the Scripts folder.
3. Follow the steps to add a new web form to the project.
17
How to do it
Following are the steps to add jQuery to ASP.NET web project using the
ScriptManager control:
1. Open the web form in the Design mode.
2. 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.
3. Go to Toolbox | AJAX Extensions, and drag and drop the ScriptManager control onto
the form:
4. 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:
18
Chapter 1
5. 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
19
7.
Open the Default.aspx web form in the Source mode. Add the following
ScriptReference to the ScriptManager control:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>
20
Chapter 1
When using the ScriptManager control to add a reference
to the jQuery library, the jQuery code should be placed after the
ScriptManager control, that is, after the jQuery reference has
been declared; otherwise, the page will throw an error. It is also
important to note that the ScriptManager control should reside
inside the <form> element.
8. To retrieve the jQuery files from CDN, set the EnableCdn property of the
ScriptManager control to true, as follows:
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableCdn="true">
<Scripts>
<asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>
How it works
This is how the ScriptManager control works:
1. The ScriptManager control can be used to load JavaScript files, such as the
jQuery library. This can be done by adding the ScriptReference to jQuery in
the ScriptManager control, as follows:
<asp:ScriptReference Name="jquery"
/>
Description
This is the release path of the script resource
DebugPath
CdnPath
CdnDebugPath
CdnSupportsSecureConnection
LoadSuccessExpression
5. If EnableCdn is set to true, the script is served from the CDN path, that is, from
CdnDebugPath in the development/debug mode and CdnPath in the release mode.
6. 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 the ScriptManager control adds a fall back
mechanism when the CDN is unavailable and files are served locally instead:
See also
The Adding jQuery to an empty ASP.NET web project using a script block recipe
22
Chapter 1
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.
Getting ready
1. 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).
2. Follow the steps in the previous recipe to add the jQuery library (the uncompressed
and compressed formats) to the Scripts folder.
3. 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:
23
5. 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:
24
Chapter 1
How to do it
To incorporate jQuery in an ASP.NET Master Page, follow these steps:
1. 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 the ScriptManager
control (refer to the Adding jQuery to an empty ASP.NET web project using the
ScriptManager control recipe), as shown in the following screenshot:
25
How it works
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:
See also
The Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe
26
Chapter 1
Getting ready
1. 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).
2. Add a new Web Form to the project and name it Default.aspx.
3. Add the jQuery library files to the Scripts folder.
4. 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.
How to do it
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
Page.
27
How it works
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.
See also
The Adding jQuery to an empty ASP.NET web project using a script block recipe
How to do it...
Here are the steps to create an ASP.NET web application using the default web
application template:
1. 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.
2. 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:
28
Chapter 1
3. Open the Site.Master Master Page in the Source mode, as shown in the
following screenshot:
29
How it works
When you follow the preceding steps, this is how the web application is mapped to the
jQuery library:
1. The ScriptManager control switches the jQuery library between the development
and release versions, depending on the debug attribute of the <compilation>
element in web.config:
<compilation debug="true"/>
2. When the debug attribute is true, the uncompressed version is used. When debug
is false, the minified version is used.
3. The default template is shipped with the AspNet.ScriptManager.jQuery
package. This package adds the following ScriptMappings to jQuery in the
PreApplicationStart 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"
});
The default Web Forms template adds the Microsoft CDN URL,
as shown in the preceding code.
Chapter 1
5. 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:
31
By running the page and viewing the source in the browser window, note that
Microsoft CDN is replaced with Google CDN as required:
See also
The Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe
Getting ready
1. 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).
2. Add a new Web Form to the project.
3. Add the jQuery library files to the Scripts folder.
4. Add a reference to the jQuery library on the web form using any method of
your choice.
32
Chapter 1
5. 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>
How to do it
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>
How it works
Following are the steps to print Hello World!! in a web project using jQuery:
1. In the preceding jQuery code, the $ symbol is used to instantiate the jQuery object.
2. The .ready() function is triggered when the DOM is ready. It is commonly used to
execute the required jQuery code on the page.
3. The Label control can be accessed from the jQuery code using ASP.NET's ClientID
property and jQuery's #identifier selector.
33
See also
The Hello World in ASP.NET MVC using jQuery recipe
34
Chapter 1
Getting ready
1. 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:
35
3. This will launch the Add Scaffold dialog box. Select MVC 5 Controller Empty,
and click on the Add button:
36
Chapter 1
4. On being prompted to add a name for the controller, type HomeController and
click on the Add button:
5. 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:
37
7.
38
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 for web.optimization,
as shown in the following screenshot. Click on the Install button to download and
install the latest version:
Chapter 1
8. Lastly, create a Scripts folder in the project and include the jQuery library files in
the folder.
How to do it
Follow these steps to bundle jQuery in ASP.NET MVC:
1. Open the BundleConfig class in the App_Start folder in the MVC project. If the
file does not exist, create a new module (VB)/class (C#) in the App_Start folder,
and name it BundleConfig.vb/BundleConfig.cs.
2. In BundleConfig.vb/BundleConfig.cs, add a namespace to System.Web.
Optimization at the top of the file:
For VB, the code is as follows:
Imports System.Web.Optimization
39
4. 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
40
Chapter 1
6. 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
7.
Next, add the script reference for jQuery to the view in the <head> element
as follows:
@Scripts.Render("~/Scripts/jquery")
How it works
Bundling jQuery in ASP.NET MVC can be done by following these steps:
1. 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.
2. When the debug mode is on, the corresponding debug version is used. In the release
mode, the minified version is bundled.
3. 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:
41
See also
The Using a CDN to load jQuery in MVC recipe
Getting ready
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.
How to do it
Following are the steps to load jQuery in MVC:
1. In the BundleConfig module/class, modify the RegisterBundles method in
order to set the UseCdn property to true, as shown in the code snippet in step 2.
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
42
Chapter 1
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"));
}
}
How it works
Following are the steps to load jQuery in MVC using CDN:
1. By setting the UseCdn property, serving of bundled scripts from the CDN is enabled.
2. 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.
3. 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>
See also
The Hello World in ASP.NET MVC using jQuery recipe
Getting ready
Use the MyMvcApplication project created in the Bundling jQuery in ASP.NET MVC recipe.
43
How to do it
Following are the steps to write simple jQuery code:
1. Open the Index view, and add the following markup to the <body> element:
<div id="divMessage">
</div>
3. Right-click on the Index view, and select View in Browser (Internet Explorer).
How it works
Following are the steps to print Hello World in ASP.NET MVC using jQuery:
1. The $ symbol is used to instantiate the jQuery object.
2. The .ready() function is triggered when the DOM is ready. It is commonly used to
execute the required jQuery code on the page.
3. The HTML <div> element with id = "divMessage", which is used to display
the Hello World message, can be accessed using its ID with jQuery's #identifier
selectorthat is, using the #divMessage selector.
4. Using the .css() property of the jQuery object, the font style, size, and text of the
<div> element are manipulated so that the following output is displayed on running
the application:
44
Chapter 1
See also
The Bundling jQuery in ASP.NET MVC recipe
45
Getting ready
1. 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:
How to do it
Debugging jQuery code in Visual Studio can be done by performing the following steps:
1. 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:
46
Chapter 1
2. 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:
47
5. 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.
6. Press Shift + F5 to stop debugging.
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.
See also
The Hello World in a web project using jQuery recipe
48
www.PacktPub.com
Stay Connected: