ASP.NET jQuery Cookbook for Developers

This text provides excerpts from the second edition of the ASP.NET jQuery Cookbook, originally published in 2011 and updated in 2016 by Packt Publishing. It serves as a practical guide with recipes for integrating jQuery with ASP.NET web forms and MVC applications. Key topics covered include setting up and managing jQuery libraries, utilizing jQuery selectors to interact with controls, handling various events, manipulating the Document Object Model (DOM), adding visual effects, and performing Ajax calls. The book also guides readers on creating and using jQuery plugins, including leveraging NuGet for package management and debugging techniques within Visual Studio.

Podcast

Listen or Download Podcast – ASP.NET jQuery Cookbook for Developers

Exploring jQuery in ASP.NET Applications

Based on the provided sources, here is a discussion about jQuery:

jQuery is a lightweight JavaScript library that has transformed the landscape of client scripting in web applications. Developed by John Resig in 2006, it quickly gained popularity due to 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. Using jQuery simplifies many client scripting tasks, including event handling, embedding animations, and writing Ajax-enabled pages, contributing to a more interactive experience for the end-user. Its extensible plugin architecture also allows developers to build additional functionalities on top of the core library.

The library consists of a single JavaScript (.js) file. At the time the source was written, jQuery was available in two major versions: Version 1.x and Version 2.x. While the Application Programming Interface (API) is the same for both, Version 2.x does not support older browsers like IE 6, 7, and 8, whereas Version 1.x continues to support them. You can download jQuery in either uncompressed format (for development and debugging) or compressed format (for production, also known as the minified version). The minified version uses optimization techniques like removing whitespaces and shortening variable names, making it smaller but harder to read. A map file (.min.map) is available to simplify debugging of the minified version by mapping it back to its unbuilt state.

Including jQuery in an ASP.NET application can be done in several ways:

  • Downloading from jQuery.com and manually adding the file to your project.
  • Using a Content Delivery Network (CDN), which hosts the jQuery library on distributed servers. This can improve performance as users might already have the file cached from visiting other sites that use the same CDN. Available CDNs include jQuery’s CDN, Google CDN, Microsoft CDN, CDNJS CDN, and jsDelivr CDN. Using a CDN means linking directly to the library file hosted online instead of using a local copy. Note that CDNs might take a couple of days to update with the latest jQuery releases.
  • Using the NuGet Package Manager, available with Visual Studio, which simplifies installing and upgrading the library within your project. NuGet typically downloads the debug (.js), release (.min.js), Intellisense (.intellisense.js), and map (.min.map) files into the project’s Scripts folder.
  • Adding jQuery to an empty ASP.NET web project using a script block (<script>) by referencing the local file path. This method requires manual updates if the library version changes and manual switching between debug and release versions.
  • Adding jQuery to an empty ASP.NET web project using the ScriptManager control. This control helps manage script references, automatically switching between debug and release versions based on the <compilation debug=”true”/> setting in web.config. It can also be configured to load jQuery from a CDN if the EnableCdn property is set to true. The ScriptManager uses a ScriptResourceDefinition object, typically defined in the Global.asax file, to map a script name (like “jquery”) to its local and CDN paths for debug and release modes. It also includes a fallback mechanism to load the local copy if the CDN is unavailable.
  • Adding jQuery to an ASP.NET Master Page ensures that all content pages using that Master Page automatically include the library. This can be done by adding the <script> block or ScriptManager control to the Master Page.
  • Adding jQuery programmatically to a web form using the Page.ClientScript.RegisterClientScriptInclude method in the code-behind file. This method adds the script block within the <form> element.
  • In the default ASP.NET Web Application templates, jQuery is often included using the ScriptManager control in the Master Page, leveraging the Microsoft CDN by default, with mapping defined by the AspNet.ScriptManager.jQuery package. This mapping can be changed to use a different CDN, such as Google CDN, by updating the ScriptResourceMapping in the BundleConfig class.
  • In ASP.NET MVC applications, jQuery can be included using the <script> tag in views. A common method is using bundling, which combines multiple script files into a single file to reduce HTTP requests. Bundling is configured in the BundleConfig class using ScriptBundle. Bundling can also be configured to load jQuery from a CDN by setting the UseCdn property and providing the CDN path. A fallback mechanism should be included in the view to load the local file if the CDN fails.

Once jQuery is included, you can write client-side code to interact with your web page. A common starting point is using the $(document).ready() function, which executes code when the Document Object Model (DOM) is fully loaded.

jQuery provides powerful features for manipulating elements on a web page:

  • Selectors: These are jQuery constructs used to retrieve elements based on specified conditions. They can return single or multiple elements. Since ASP.NET controls are rendered as HTML elements, they can be selected using standard jQuery selectors. Types of selectors include Basic selectors (by tag, class, ID, or combination), Hierarchy selectors (selecting based on relationships like parent/child), Attribute selectors (selecting based on element attributes), Form selectors (working with form elements), and Position filters (selecting elements based on their position in a collection). Examples of selectors used in the sources include #identifier for selecting by ID, .class for selecting by CSS class, html_tag for selecting by HTML tag, [attribute*=”value”] for selecting by attribute containing a value, :first, :last, :odd, :even, :eq(i), :lt(i), :gt(i) for position filtering. The $(this) object refers to the current jQuery object in a chain or callback.
  • DOM Traversal: jQuery provides methods to navigate the DOM tree, such as accessing parent (.parent(), .parents()), child (.children(), .find()), and sibling (.siblings()) elements.
  • DOM Manipulation: Elements can be added (.append(), .prepend(), .appendTo()), removed (.remove()), or cloned (.clone()) at runtime using client code. Methods like .addClass() and .removeClass() are used to manage CSS classes.
  • Visual Effects and Animations: jQuery simplifies adding visual effects. Built-in methods include .show(), .hide(), .toggle() for displaying elements; .fadeIn(), .fadeOut(), .fadeTo(), .fadeToggle() for fading; and .slideUp(), .slideDown(), .slideToggle() for sliding effects. Custom animations can be created with .animate() by changing numeric CSS properties over time. Animations can be stopped using .stop() or .finish(). The duration of animations can be specified in milliseconds or using keywords like “slow” and “fast”. Specific applications of effects mentioned include animating Menu controls, creating digital clocks, animating AdRotator alt text, animating images in TreeView nodes, creating scrolling text, building vertical accordion menus, and showing/hiding GridView controls. The jQuery UI library provides additional effects like “explode” and enhanced easing methods like “easeOutBounce”.
  • Event Handling: Events occur when a user interacts with the page or during page milestones. An event handler is a function executed when an event occurs. jQuery 1.7+ recommends the .on() method for binding event handlers. It can attach single events, multiple events to one handler, or different events to different handlers. Event delegation is a technique where a single event handler is attached to a parent element to manage events for its children, including future children. This is possible due to event bubbling, where events in a child element travel up the DOM tree. Event bubbling can be stopped using .stopPropagation(). The .one() method attaches an event handler that executes at most once. Events can be triggered programmatically using .trigger(). Data can be passed with events, typically as a JSON string. Events can also use namespacing (e.g., click.myNamespace) to group handlers. Event handlers can be removed using .off(). Examples of events discussed include mouse events (mouseover, mouseout, click, dblclick, mousemove), keyboard events (keyup), and form events (focus, blur, change).
  • Working with Graphics: jQuery aids in integrating graphics by providing utilities for effects, animations, and event handlers on elements like <img>, ImageButton, and ImageMap. Examples include creating spotlight effects on images, zooming images on mouseover, building image scrollers, creating photo galleries (using z-index or ImageMap), using images in Menu controls, creating a 5-star rating control (as a User Control), and previewing image uploads in MVC. The File API (window.File, window.FileReader) and its onloadend event are used for previewing image uploads.
  • Ajax (Asynchronous JavaScript and XML): Ajax allows communication with the server without full page refreshes, updating parts of the page transparently. jQuery simplifies Ajax with methods like the generic .ajax() for various request types (GET, POST, etc.). Global default settings can be configured with .ajaxSetup(). Shortcut methods like .load() (for text/HTML content) and .getJSON() (for JSON data via GET) are also available. jQuery Ajax can be used to consume various server-side endpoints in ASP.NET, including page methods (static/shared methods marked with [WebMethod]), Web services (ASMX), WCF services (Ajax-enabled SVC), Web API (HTTP API), and generic HTTP handlers (ASHX). The $.getJSON() method is particularly useful for retrieving JSON data from endpoints like Web APIs. For WCF services and page methods expecting JSON input, contentType: “application/json; charset=utf-8” and data as a JSON string are used. Accessing returned data from Web Services, WCF Services, and Page Methods often involves accessing a .d property of the response object.
  • Plugins: jQuery’s plugin architecture allows extending the core library. Plugins are JavaScript files included alongside jQuery. They typically provide configurable functionalities. New plugins are published to the NPM (Node Package Manager) repository. Creating a plugin involves defining methods in the jQuery namespace (for utility functions like $.sampleMethod()) or on jQuery.fn (alias for jQuery.prototype, for methods callable on DOM elements like $(“#element”).myMethod()). Using a wrapping function (function($){…})(jQuery) allows using the $ alias safely within the plugin, even if $.noConflict() has been called elsewhere. Plugin methods often use .each() to ensure they operate correctly on collections of matched elements. Good practices for plugins include providing default options using $.extend() to allow customization and returning the this object (the jQuery object) to enable method chaining. Plugins can also define different actions or functionalities based on arguments passed to the method. The jQuery validation plugin is a popular example available from http://jqueryvalidation.org and downloadable via package managers like NuGet or Bower (which requires Node.js, NPM, and Git). This plugin provides methods like .validate() to validate forms based on defined rules and messages, and .resetForm() to clear validations. It offers features like custom error message placement and handling invalid forms.

This book aims to impart the skill of learning jQuery and using it in ASP.NET applications by exploring diverse recipes for common problems in ASP.NET 4.6 applications. The examples are based on Visual Studio 2015 and jQuery 2.1.4 and were tested in Internet Explorer 11.0.96, Mozilla Firefox 38.0.1, and Google Chrome 47.0.2526. Familiarity with Visual Studio and MS SQL Server is preferred but not mandatory for the reader.

jQuery and ASP.NET Development Guide

Based on the sources you provided, ASP.NET is a framework used for creating web applications. The book specifically focuses on writing client script using jQuery in ASP.NET 4.6 applications. Sonal Aneel Allana, the author, has experience teaching in areas including .NET and ASP.NET.

The sources describe how to integrate and use the jQuery library within ASP.NET Web Forms and MVC applications. The book covers various aspects of using jQuery with ASP.NET, including:

  • Getting Started with downloading and including jQuery in ASP.NET 4.6 Web and MVC projects. This involves understanding CDNs, using NuGet Package Manager, adding jQuery via script blocks, using the ScriptManager control, adding it to ASP.NET Master Pages, and adding it programmatically to web forms. The default Web Application template in ASP.NET also includes a reference to jQuery, typically using the ScriptManager control.
  • Using jQuery Selectors with ASP.NET Controls. When an ASP.NET page is viewed in a browser, controls are rendered as HTML elements, making them selectable with standard jQuery selectors. The book demonstrates selecting controls by ID, CSS class, HTML tag, attribute, or position in the DOM. Selectors can also be used in ASP.NET MVC applications.
  • Event Handling Using jQuery in ASP.NET. This includes responding to mouse, keyboard, and form events, as well as using event delegation and detaching events.
  • DOM Traversal and Manipulation in ASP.NET. Techniques covered include accessing parent, child, or sibling elements, refining selection using filters, and adding or removing elements at runtime.
  • Visual Effects in ASP.NET Sites. Recipes discuss creating animation effects on various ASP.NET controls like Panel, AdRotator, TreeView, Menu, and GridView.
  • Working with Graphics in ASP.NET Sites and MVC. This involves applying effects like zooming and scrolling to images and building components like image galleries, image previews, and rating controls using jQuery. ASP.NET server controls such as Image, ImageButton, and ImageMap, as well as plain HTML image elements in MVC, can be manipulated.
  • Ajax Using jQuery in ASP.NET. The book explains how to make Ajax calls to interact with server-side components such as page methods, Web services (.asmx), WCF services (.svc), Web API, MVC controllers, and HTTP handlers (.ashx).

To work with the examples discussed, requirements include Visual Studio 2015, MS SQL Server 2014, the Northwind database, the jQuery library, the jQuery UI library, a web browser, NPM, and Bower. The book is aimed at ASP.NET developers who want to use jQuery to write client scripts for cross-browser compatibility. While familiarity with Visual Studio and MS SQL Server is preferred, it is not compulsory.

Mastering jQuery Selectors in ASP.NET

Based on the sources, jQuery selectors are fundamental constructs used to retrieve elements on a web page based on a specified condition. They provide a mechanism to access web page elements when writing client scripts, which is essential for manipulating these elements. While standard JavaScript allows accessing elements by their unique IDs using methods like document.getElementById(), selectors offer more flexibility, enabling developers to select elements based on attributes other than ID, or to retrieve and manipulate multiple elements simultaneously.

Selectors are particularly relevant in the context of ASP.NET development because when an ASP.NET page is viewed in a browser, the server controls are rendered as HTML elements. This conversion means that standard jQuery selectors can be applied to manipulate these rendered ASP.NET controls just like any other HTML element. The sources provide a table illustrating the mapping of common ASP.NET controls to their rendered HTML elements and tags, such as GridView rendering as <table>, Button as <input type=”submit”/>, and Label as <span>. Selectors are also usable in ASP.NET MVC applications as they typically use raw HTML markups or HTML helper methods to render content.

The sources classify jQuery selectors into several broad types:

  • Basic selectors: These are similar to CSS selectors and are used to retrieve elements based on their HTML tag, CSS class, element ID, or a combination. Examples include selecting all elements ($(“*”)), all <div> elements ($(“div”)), all elements with a specific CSS class ($(“.highlight”)), an element with a specific ID ($(“#footer”)), or a combination.
  • Hierarchy selectors: Also resembling CSS selectors, these are used to select child or descendant elements within the structure of the Document Object Model (DOM) tree. Examples include selecting all <p> elements inside <div>s ($(“div p”)) or immediate children <p> of <div>s ($(“div > p”)).
  • Attribute selectors: These selectors retrieve elements based on the attributes they possess. Examples include selecting all <a> elements with an href attribute ($(“a[href]”)), or those whose href attribute contains ($(“*=”)), starts with ($(“^=”)), or ends with ($(“$=”) a specific string.
  • Form selectors: Specifically designed to work with various form elements like inputs, checkboxes, and radio buttons. Examples include selecting elements by type ($(“:button”), “:checkbox”, “:radio”), all form elements ($(“:input”)), or elements based on state (“:checked”, “:selected”, “:enabled”, “:disabled”).
  • Position filters: These selectors retrieve elements based on their position within a collection, often relative to siblings. Examples include selecting the first element in a collection (:first), the last (:last), those at an odd or even index (:odd, :even), at a specific index (:eq(i)), or with an index less than (:lt(i)) or greater than (:gt(i)) a certain value.

Anonymous functions are frequently used in conjunction with selectors, often passed as arguments to other functions that operate on the selected elements.

The sources provide several recipes demonstrating the practical application of these selectors within ASP.NET applications:

  • Using the ID selector (#identifier) to access controls like TextBox, RadioButtonList, DropDownList, CheckBoxList, CheckBox, and Button in a web form. This often involves using the ASP.NET ClientID property to get the rendered HTML ID.
  • Employing the CSS class selector (.class) to work with controls like Image, Panel, and BulletedList.
  • Selecting controls like GridView by their rendered HTML tag ($(“html_tag”)), often combined with attribute filters or hierarchy selectors to target specific parts like rows (<tr>) or cells (<td>).
  • Accessing controls like Hyperlink based on their attributes, such as the href attribute rendered from the NavigateUrl property.
  • Selecting list items (<option> rendered from ListItem in ListBox or DropDownList) or other elements based on their position within the DOM, using position filters like :first-child, :last-child, :lt(), :gt(), and :nth-child.
  • Using selectors to dynamically enable or disable controls on a web form.
  • Demonstrating the use of various selectors within ASP.NET MVC applications.

A link to http://api.jquery.com/category/selectors is mentioned as a resource to find out more about different types of jQuery selectors.

jQuery Event Handling Fundamentals

Based on the sources, event handling is a fundamental concept in client scripting using jQuery in ASP.NET applications.

An event is defined as an action that occurs when the user interacts with the web page or when certain milestones are completed, such as a page loading in the browser. Examples include moving the mouse, pressing a key, clicking a button or link, keying in text in a field, or submitting a form. Events can be user- or system-initiated.

An event handler is a function that is executed when a specific event occurs. Writing or binding an event handler for a particular event allows developers to program the desired actions in response to user or system interactions. jQuery eases client scripting tasks, including event handling, adding to the interactive experience for the end user.

When working with events, event delegation is an important mechanism. It allows you to attach a single event handler to a parent element instead of attaching individual event handlers to each child element. This approach optimizes the number of event handlers on the page. Event delegation is also useful for wiring events to child elements that do not exist when the page initially loads but are added later at runtime.

Event delegation is made possible because of event bubbling. Event bubbling is the process where an event occurring in a child element travels up the Document Object Model (DOM) tree to its parent, then to its parent’s parent, and so on, until it reaches the root element (the window). For example, a click event on a table cell (<td>) bubbles up through the table row (<tr>), the table (<table>), and eventually to the <body>, <html>, and window elements. The parent element can intercept the event as it bubbles up, allowing a single handler on the parent to manage events for its descendants. jQuery provides a .stopPropagation() method to prevent an event from bubbling further up the DOM tree.

jQuery offers several methods for binding events. Prior to jQuery 1.7+, methods like .bind(), .live(), and .delegate() were used. However, these are now deprecated, and the .on() method is recommended for event binding in jQuery 1.7+.

The .on() method can be used in various ways:

  • Attaching a single event to a handler: For example, $(“#btnTest”).on(“click”, function(){…});.
  • Attaching multiple events to a handler: The same handler can respond to multiple events listed with spaces, like $(“#imgTest”).on(“mouseover mouseout”, function(){…});.
  • Attaching different events to different handlers: An object can be passed mapping event names to handler functions, for example, $(“#imgTest”).on({ mouseover: function(){…}, mouseout: function(){…} });.
  • Event delegation: By specifying a selector as a second argument, the handler is attached to the parent element but only executed for descendant elements matching the selector. For example, $(“#tblTest”).on(“click”, “tr”, function(){…}); attaches the click handler to the table, but it only runs when a table row (<tr>) inside the table is clicked. This is demonstrated in a recipe to attach events to dynamically added rows.
  • Passing data to events: Data can be passed as a JSON string or other data types when binding the event, which can then be accessed in the event handler. This is demonstrated in a recipe using the .trigger() method.

Specific types of events discussed in the sources include:

  • Mouse events: Such as mouseover (when the mouse pointer enters an element) and mouseout (when it leaves an element). The .hover() method is a shortcut for binding mouseover and mouseout handlers. A recipe demonstrates handling these events to display a custom tooltip for text boxes.
  • Keyboard events: Such as keyup (when a key is released). Other keyboard events mentioned are keydown and keypress. A recipe uses the keyup event to create a character count for a text area.
  • Form events: Such as focus (when an element receives focus) and blur (when an element loses focus). A recipe uses these events to apply styles and display background text or validation errors on form controls.

In the context of ASP.NET, when a page is viewed in the browser, server controls are rendered as HTML elements. This means that standard jQuery event handling techniques, including the use of selectors and the .on() method, can be applied to these rendered HTML elements corresponding to ASP.NET controls.

To ensure an event handler is executed at most once, the .one() method can be used. Once the event is triggered and the handler is executed, the handler is automatically detached from the element. This is shown in a recipe for a “See More…” link that should only work once.

jQuery’s .trigger() method allows events to be invoked programmatically. This means client-side code can simulate user actions or system events. A recipe demonstrates using .trigger() to simulate a click on an “Edit” link in a GridView row when the user double-clicks the row itself.

Events can also have event data passed along with them and can utilize event namespacing. Namespacing allows multiple handlers to be attached to the same event type for the same element without interfering with each other; handlers can then be triggered or detached based on their namespace. A recipe illustrates passing data as a JSON object and using namespacing (click.radioclick1, click.radioclick2) to trigger different alert or confirm boxes based on which radio button was clicked.

Finally, the .off() method is used to detach event handlers from elements. It can remove specific handlers, all handlers for a particular event type, or all handlers (including namespaced ones) depending on how it is used. A recipe shows how to use .off() to remove focus and blur event handlers from text boxes when a checkbox is unchecked.

DOM Traversal and Manipulation with jQuery

Based on the sources, DOM manipulation is a key concept when working with client scripts like jQuery in ASP.NET applications.

The Document Object Model (DOM) is presented as a representation of web pages in a structured, tree-like format. Each part of the web page is a node in this tree, and these nodes have properties, methods, and event handlers. The web page itself is the document object, accessible via window.document. HTML elements on the page become element nodes, such as <head> or <body>, which can have children nodes like <table>, <div>, or <input>. The DOM is described as an object-oriented model that is language-independent, offering a common Application Programming Interface (API) that allows programming languages like JavaScript to manipulate the style, structure, and content of web pages.

jQuery provides many methods for interacting with the DOM, including manipulating elements.

One specific aspect of DOM manipulation discussed is adding and removing DOM elements. jQuery offers methods to perform these actions at runtime using client code.

The sources illustrate adding DOM elements using the .clone() method. This method creates a deep copy of the matched elements, including their descendants and text nodes. When cloning elements, it’s necessary to update properties like ID, name, and value of the cloned elements and their children to avoid duplicates. The cloned elements can then be added to the DOM using methods like .appendTo(), which inserts the elements at the end of a target element. A recipe demonstrates cloning a Panel control (addPanel CSS class) and its contents, updating the IDs and names of the cloned elements, and appending them to a container div.

For removing DOM elements, the jQuery method .remove() is used. This method not only removes the matched elements but also their descendants, and it removes all related data and events associated with them. A recipe shows how to remove a dynamically added Panel control using its ID and the .remove() method after user confirmation.

The sources also touch upon other manipulation strategies, such as adding items to controls at runtime. This involves using methods like .prepend() to insert content at the beginning of a matched element or .append() to insert content at the end. The $.map() function can be used to transform data (like an array of strings) into an array of DOM elements (<option> or <li>) before appending/prepending them. This is demonstrated in a recipe for adding items to ListBox, DropDownList, and BulletedList controls dynamically.

While focusing on manipulation, the sources also reference DOM traversal as a related concept. Traversal methods allow accessing elements in the DOM tree, such as parent, child, or sibling elements. Examples of traversal methods mentioned or used in the context of accessing controls (though not explicitly manipulation methods) include .parent() to get the immediate parent, .children() for immediate descendants, .find() for descendants matching a filter, .siblings() for elements on the same level, .next() for the immediate sibling, and filtering selections using methods like .filter(). These traversal methods are often used before performing manipulation on the selected elements.

Chapter 4 of the source material is specifically dedicated to “DOM Traversal and Manipulation in ASP.NET”, covering recipes on adding/removing elements, accessing parent/child controls, accessing sibling controls, refining selection using filters, and adding items to controls at runtime.

Download PDF Book

Read or Download PDF Book – ASP.NET jQuery Cookbook for Developers

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog


Discover more from Amjad Izhar Blog

Subscribe to get the latest posts sent to your email.

Comments

Leave a comment