Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
ASP.NET jQuery Cookbook (Second Edition)
ASP.NET jQuery Cookbook (Second Edition)

ASP.NET jQuery Cookbook (Second Edition): Over 60 recipes for writing client script in ASP.NET 4.6 applications using jQuery , Second Edition

Arrow left icon
Profile Icon Aneel Allana Profile Icon Sonal Merchant
Arrow right icon
€45.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Feb 2016 478 pages 2nd Edition
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Aneel Allana Profile Icon Sonal Merchant
Arrow right icon
€45.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
Paperback Feb 2016 478 pages 2nd Edition
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

ASP.NET jQuery Cookbook (Second Edition)

Chapter 1. Getting Started with jQuery in ASP.NET

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

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.

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.

Downloading jQuery from jQuery.com

This recipe explains how to download jQuery on your system along with the version/build to use and the supporting files that are required.

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:
    Getting ready
  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:
    Getting ready

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:

  • Uncompressed format: This is used in a development environment or when debugging the code.
  • Compressed format: This is used in a production (that is, release) environment. It is compact and uses low bandwidth. It is commonly referred to as the minified version.

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:

How to do it…

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.

Understanding CDN for jQuery

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.

How to do it…

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

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

The Google CDN

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/jquery-2.x.x.js

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.js

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.x.x.min.map

Version 1.x:

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.js

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.js

http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.x.x.min.map

The CDNJS CDN

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

The jsDelivr CDN

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

Using CDNs for new releases

Note that CDNs may not have the latest files when new versions of the jQuery library are launched since it usually takes a couple of days for third-parties to update their files. In the case of new releases, always check the available version before downloading them.

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.

See also

The Using NuGet Package Manager to download jQuery recipe

Using NuGet Package Manager to download jQuery

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.

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:

Getting ready

Alternatively, right-click on the project in the Solution Explorer tab, and select Manage NuGet Packages.

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:

    How to do it…

    Tip

    Searching for packages in NuGet

    If jQuery is not visible in the left-hand side panel, you need to search for it by keying in jQuery in the search box in the top left corner of the NuGet Manager screen.

  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:

How it works…

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

See also

The Downloading jQuery from jQuery.com recipe

Adding jQuery to an empty ASP.NET web project using a script block

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.

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:
    Getting ready

    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.

  2. 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:

    Getting ready

  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:
    Getting ready
  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:
    Getting ready

Note

In the remaining recipes, when asked to create a Web Application project using the Empty template, follow the steps listed in this section.

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:
    How to do it…
  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:
    How to do it…
  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:
    How to do it…
  4. 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:
    How to do it…
  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>

    For release mode, the code is as follows:

    <script src="Scripts/jquery-2.1.4.min.js"></script>
    How to do it…

See also

The Downloading jQuery from jQuery.com recipe

Adding jQuery to an empty ASP.NET web project using ScriptManager control

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.

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.

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:
    How to do it…
  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:
    How to do it…

    Note

    The Global.asax file is an optional file that resides in the root directory of the application and responds to events at the application and session levels, such as the starting and ending an application or session.

  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

    For C#, the code is as follows:

    using System.Web.UI;
  6. In the Application_Start event in the Global.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"
        });
    }
  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>

    Note

    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"  />
  2. However, we require to define this mapping. This can be done in the Global.asax file using a ScriptResourceDefinition object, which exposes the following properties:

    Property

    Description

    Path

    This is the release path of the script resource

    DebugPath

    This is the development/debug path of the script resource

    CdnPath

    This is the release path of the script resource served from a CDN

    CdnDebugPath

    This is the development/debug path of the script resource served from a CDN

    CdnSupportsSecureConnection

    This indicates whether the HTTPS mode needs to be used to retrieve the resource when the page is accessed using a secure connection

    LoadSuccessExpression

    This is the JavaScript expression that detects whether a JavaScript file has been loaded successfully

  3. The ScriptResourceDefinition object defined in Global.asax is named jquery. The ScriptManager control uses the same name to load the reference on the web form.
  4. In the development/debug mode, the script is served from DebugPath while in the release mode, it is served from Path.

    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 the web.config to true as follows:

    <system.web>
        <compilation debug="true"/>
        …..
    </system.web>  

    When the debug attribute is set to false, the application will run in the release mode.

  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:
    How it works…

See also

The Adding jQuery to an empty ASP.NET web project using a script block recipe

Adding jQuery to an ASP.NET Master Page

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.

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:
    Getting ready
  4. 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:
    Getting ready
  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:
    Getting ready

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:
    How to do it…
    How to do it…

    Note

    When using the <script> block, the jQuery 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 the ContentPlaceHolder in which the jQuery code will be added later to the content pages. The Global.asax file should also be updated in order to add the required ScriptResourceDefinition , as described in the Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe.

  2. The required jQuery code can now be added to the ContentPlaceHolder (with ID = "ContentPlaceHolder1") in the Default.aspx web form.

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:

How it works…

See also

The Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe

Adding jQuery programmatically to a web form

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.

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

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"));
}

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:

How it works…

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

Understanding jQuery reference in the default web application template

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.

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:
    How to do it...
  3. Open the Site.Master Master Page in the Source mode, as shown in the following screenshot:
    How to do it...
  4. Notice that the ScriptManager control that is added to the <form> element has the following reference to jQuery:
    <asp:ScriptReference Name="jquery" />

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"
    });

    Note

    The default Web Forms template adds the Microsoft CDN URL, as shown in the preceding code.

  4. When the EnableCdn property of the ScriptManager control is set to true, CdnPath and CdnDebugPath are used in release and development modes, respectively, to serve scripts from the Microsoft CDN:
    <asp:ScriptManager runat="server" EnableCdn="true">
  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:
    How it works…
  6. To change the CDN to another, for example Google CDN, we need to change ScriptResourceMapping in the RegisterBundles method in BundleConfig, as shown in the following code. This module/class is located in the App_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"
    });
  7. By running the page and viewing the source in the browser window, note that Microsoft CDN is replaced with Google CDN as required:
    How it works…
  8. Open the Global.asax page to view the registration of bundles in the Application_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);

See also

The Adding jQuery to an empty ASP.NET web project using the ScriptManager control recipe

Hello World in a web project using jQuery

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.

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.
  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.
  4. Using the .css() property of the jQuery object, the font style, size, and text of the Label control are manipulated so that the following output is displayed on running the application:
    How it works…

See also

The Hello World in ASP.NET MVC using jQuery recipe

Bundling jQuery in ASP.NET MVC

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.

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:
    Getting ready
  2. 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:
    Getting ready
  3. This will launch the Add Scaffold dialog box. Select MVC 5 Controller – Empty, and click on the Add button:
    Getting ready
  4. On being prompted to add a name for the controller, type HomeController and click on the Add button:
    Getting ready
  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:
    Getting ready
  6. 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:
    Getting ready

    Note

    In the remaining recipes, when asked to create a MVC application, follow steps 1 to 6 as mentioned earlier.

  7. 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:
    Getting ready
  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

    For C#, the code is as follows:

    using System.Web.Optimization;
  3. Register and configure a bundle for jQuery in the RegisterBundles method in BundleConfig 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"));
        }
    }
  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

    For C#, the code is as follows:

    BundleTable.EnableOptimizations = true;
  5. In the Global.asax file, include the namespace for System.Web.Optimization, as shown in step 2 mentioned previously. Then, register the bundle in the Application_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);
  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

    For C#, the code is as follows:

    @using System.Web.Optimization
  7. 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.

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:
    How it works…

See also

The Using a CDN to load jQuery in MVC recipe

Using CDN to load jQuery in MVC

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.

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

    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"));
         }
    }

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

Hello World in ASP.NET MVC using jQuery

This recipe demonstrates how to write a simple jQuery code to display Hello World in the ASP.NET MVC project.

Getting ready

Use the MyMvcApplication project created in the Bundling jQuery in ASP.NET MVC recipe.

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>
  2. 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>
  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 selector—that 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:
    How it works…

See also

The Bundling jQuery in ASP.NET MVC recipe

Debugging jQuery code in Visual Studio

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.

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:
    Getting ready
  2. In the web.config file, go to the configuration/system.web/compilation element. If the element does not exist, add a new node. To enable debugging, the debug property of the <compilation> node should be set to true, as follows:
    <compilation debug="true" … />

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:
    How to do it…
  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:
    How to do it…
  3. 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.
  4. 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:
    How to do it…
  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.

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.

See also

The Hello World in a web project using jQuery recipe

Left arrow icon Right arrow icon

Key benefits

  • This is a step-by-step guide to solve common problems in ASP.NET applications
  • Easy-to-follow recipes to write client scripts effortlessly and quickly
  • A hands-on approach that will show you how to interface jQuery with ASP.NET websites and MVC

Description

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 the ability to get more done with less code. It has gained popularity with ASP.NET developers and is now distributed with Visual Studio and the NuGet package manager. 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 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 confidently with ASP.NET.

Who is this book for?

This book is for ASP.NET developers who want to use jQuery to write client scripts for cross-browser compatibility. The book assumes no prior knowledge of ASP.NET or jQuery, and every recipe is self-contained and explained in an easy-to-follow manner. Familiarity with Visual Studio and MS SQL Server is preferred, but not compulsory.

What you will learn

  • Download and include jQuery in ASP.NET websites and MVC
  • Use jQuery selectors with ASP.NET server controls
  • Get to know about event handling and DOM traversal
  • Deploy jQuery for visual effects and animations
  • Develop AJAX-enabled ASP.NET applications
  • Create your own plugins
  • Solve common problems using less code and cut down your development time
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 25, 2016
Length: 478 pages
Edition : 2nd
Language : English
ISBN-13 : 9781782173113
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Portugal

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Feb 25, 2016
Length: 478 pages
Edition : 2nd
Language : English
ISBN-13 : 9781782173113
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Bootstrap for ASP.NET MVC
€32.99
jQuery Design Patterns
€32.99
ASP.NET jQuery Cookbook (Second Edition)
€45.99
Total 111.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Getting Started with jQuery in ASP.NET Chevron down icon Chevron up icon
2. Using jQuery Selectors with ASP.NET Controls Chevron down icon Chevron up icon
3. Event Handling Using jQuery Chevron down icon Chevron up icon
4. DOM Traversal and Manipulation in ASP.NET Chevron down icon Chevron up icon
5. Visual Effects in ASP.NET Sites Chevron down icon Chevron up icon
6. Working with Graphics in ASP.NET Sites Chevron down icon Chevron up icon
7. Ajax Using jQuery Chevron down icon Chevron up icon
8. Creating and Using jQuery Plugins Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 50%
1 star 0%
Amazon Customer Mar 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very interesting cookbook that helps you put your ASP.NET knowledge and the power of jQuery into action.This book is up-to-date with the latest version of ASP.NET and jQuery. You will be able to progress smoothly from the basics to selectors, traversals, events, visual effects, Ajax, and plugins.Through the 60 recipes, you will be able to experiment with the power of jQuery in ASP.NET web forms and MVC applications.For every recipe, the author provides a list of jQuery features that will be covered in that recipe with their description!Another interesting feature about this book is the author's attention to details and full coverage. For instance, In chapter 7 that talks about Ajax, the author covers the web service examples using page methods, WCF, and Web API!! When necessary, the code is available in C# and VB.NET!
Amazon Verified review Amazon
Tom Aug 11, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The data in this book is apparently meant to be formatted 2 columns with a code example in one column, and a description of what the example represents in the second column. Unfortunately, the way the information is displayed in the kindle is (top to bottom) all the information from the first column, then information in the second column further down the page, or in many cases on a second or third page. This makes the information cumbersome at best to read/ understand. Perhaps the book formats differently on a computer, but for a kindle/ tablet user I cannot recommend the digital purchase of this book
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela