Published: 18 Aug 2008
By: Xun Ding
Download Sample Code

Let’s take a look at some of the very basics of ASP.NET AJAX and how to develop client components with the ASP.NET AJAX library

Contents [hide]

Introduction

JavaScript is nothing new. It was first introduced and deployed in Netscape 2.0 in December 1995 (incredibly ancient in Internet age). Since then, it has changed many faces and claimed a growing list of libraries. Compared to the very first version of JavaScript, today’s versions look only remotely familiar, yet definitely much more powerful. This is certainly true with the new JavaScript darling JQuery. This is also true with the ASP.NET AJAX library.

Now let us look at some of very basics about ASP.NET AJAX for a little warming up.

Rather than an inseparable mass of content, format and controls, modern web pages are structured in a hierarchy of HTML elements called DOM (Document Object Model), such as head, body, div, button, etc. The DOM provides a base on which we can access elements’ attributes and modify properties and update content dynamically.

Almost all browsers employs DOM, however all browsers do it with their own quirks, so compatibility issues are among the loudest cries. For this reason and for others (for example, aiding the communication between server and client using HttmXmlRequest, emulating the server side object-oriented programming model such as C#, VB .NET), the Microsoft AJAX library was born. It provides a set of new methods for accessing DOM elements and perform event handling.

Accessing DOM elements and performing event handling

Traditionally, supposing that we have an input button control btnTest in the form, we use JavaScript to access the DOM element as follows:

Now, with ASP.NET AJAX, we do this instead (using the shortcut $get to reference a DOM control):

With traditional JavaScript, event handling mechanism can be attached to HTML elements as part their attributes. For example, to handle a button click event:

With AJAX, this is a little different. It takes three steps:

  1. Attach an event handler to a control using $addHandler. $addHandler’s signature is: $addHandler(Element, eventName, eventHandler), with Element being a DOM element, referenced by $get() or getElementById(); EventName is the name of the event to be handled. For example, click, mouseover, or mouseout. Normally the on prefix is omitted from the $addHandler method call; eventHandler is the function name for actual event processing. Generally we attach an event handler using the $addhandler() method in the page_load event.
  2. Define the event handler in a JavaScript function specified in the $addHandler method. It takes only one parameter, the Sys.UI.DomEvent instance.
  3. Detach the event handler from its control in the page_unload event, using $removeHandler(). $removeHandler() has the same signature as $addHandler.

Example: using $addHandler to prevent a right click action

Sometimes you may want to prevent user right clicking an image from downloading it. The following example illustrates how we attach / detach an onContextMenu event handler to an image in order to accomplish this.

Listing 1: $addHandler to prevent right click

Figure 1: $addHandler example screenshot

$addHandler example screenshot

JavaScript Functions and Objects

JavaScript functions are ubiquitous, in all shapes and forms. The function as a keyword can mean almost anything. You might have heard that in JavaScript function is a first class citizen. While in real life, first class means privileges; in programming, it means being assigned to all situations, trivial or otherwise. In JavaScript, functions can be created and passed to other functions as variables, it can be used to create and instantiate objects and classes, or to process and compute, as the functions you use in C# or VB. net.

A classic function:

A function assigned to a variable:

Function as an object

In JavaScript as in other object-oriented languages, we are expected to create programming objects to mimic real life objects, encapsulating properties, behaviors and events within. In C# and VB .NET, the keyword is Class representing such abstraction; in JavaScript, function is the keyword for an object creation.

The following defines an empty object person.

Using the function in conjunction with the keyword new, we can create an instance of person.

We can fill a class with fields and methods. Normally, we use the this keyword to denote private properties of a class.

Note:

Underscore in ASP.NET AJAX is a naming convention to denote private properties of an object.

We normally define methods for getting and setting property values, and we normally do so in the prototype function of an object.

prototype sets the blueprint (properties and methods) shared by an object and all of its descendants and instances. For example, we define the property getters and setters in the person’s prototype.

We can also add any number of behaviors, methods in the prototype object:

Class in Microsoft Ajax Library

There is still one more step to elevate a JavaScript object to a class that makes sense to the Microsoft Ajax library. We need to specifically call registerClass() method to register the object into a class. registerClass() has a signature like this:

  • name: The name of the class
  • base type: The base type of the class, so that we can inherit the members and methods of the base class.
  • interface type: The interface type of the class, if any, as a reference to the type

The second and third arguments are optional. For example, the person class does not have a base type and does not implement an interface type, so we may omit the second and third arguments.

We cannot talk about JavaScript classes without talking about namespaces. Like we enclose members in classes, we group relevant classes into namespaces. First we use the method Type.registerNameSpace() to register a namespace with the AJAX library, then register the class to the namespace.

Once we have defined a class and registered it with the Microsoft AJAX library, we can easily create a child class inheriting the parent’s public and protected members. The following Child class inherits a person class but with its own work() and play() methods defined.

Listing 2: A derived class child that inherits a base class person

AJAX Client Components

So far we have rambled through some of the fundamentals in the Microsoft AJAX libraries. Now we can apply the basics to create client -side components, derived classes of the Sys.Component class.

If you can think and program through complex logic and solve real problems, you are a pretty good coder; if you can wrap the logic and all its details into one sleek component for reuse, you are a great coder. This is the case with C#, with C, with JavaScript and with all languages. No exception with the Microsoft AJAX library.

Component is an all-encompassing term. In ASP .NET AJAX, a component can be visual, associated with a DOM element, exhibiting predefined behaviors; or non-visual, which has no UI representation and no DOM association. Visual behaviors / controls and non-visual components are designed for reuse across applications.

Creating a component always takes the following four steps:

  1. Register namespace by using Type.registerNamespace()
  2. Define the component's constructor, private fields and their initial values
  3. Define the component's getting and setting methods for property value retrieval or manipulation, event handling methods and logic in the prototype.
  4. Register the component function as a class derived from Component.

We can easily modify the above created person class into a non-visual components by having it inherit from Sys.Component.

How do we create an instance of the person component and call its methods? We need to use the $create method, which takes five arguments, as in:

So we can create a person component and invoke the methods as the following:

Listing 3: Creating a person and child component and invoke the methods

Note:

Please note that you can register scripts that are required for a client control on the page with a ScriptManager control, either declaratively or programmatically as in the following example.

Note:

Please also note that we use $find, an alias for the Sys.Application.findComponent method to access a component.

Client Behaviors

The two types of visual components, behavior and controls, though having different bases classes, do not bear a great deal of differences in creation and usage. By definition, “Element behaviors are encapsulated components” attached to a DOM element for extended functionality and visual effect. Client control, on the other hand, works as a DOM element wrapper. A client control itself is a DOM element and can change the original behavior of the control it wrapped. A control can also wrap multiple controls to make into a new control. A client control class must be derived from the control class, while behavior the Sys.UI.Behavior class.

Creating client behaviors and client controls share the common steps:

  1. Define the constructor, initialize the base class and declare private properties.
  2. In the control/behavior prototype function, define Properties and raising Property-changed notification, define member methods and event handlers.
  3. Releasing Resources. Release resources by overriding the dispose method.

The following example demonstrates the process of creating a client behavior, in which a list of links are tied with a showMugShotBehavior, so whenever the event of mousing over a link, such as Bill Gates, Michael Jackson, will trigger the link to display an infamous mug shot of this person.

Listing 4: A client behavior example

We create a client behavior the same way as we do with non-visual components, by calling the $create method and specifying the DOM element with which the behavior associated with. A behavior can be associated with unlimited number of elements of different types, as both buttons and images can display the same behaviors. Take the above example: We attach the showMugShotBehavior to a hyperlink called A1.

Figure 2: ShowMugShot Behavior Screenshot

ShowMugShot Behavior Screenshot

Client Controls

Client controls are created much like client behaviors. The following is an example that demonstrates the process. It wraps up an input text control which accepts numbers only and automatically changes the inputted number into the format: #, ###, ##.

Listing 5: Code for the Test.AddCommaText control

As you can see from the above example, we use the overridden methods initialize to attach handlers for the keypress and keyup events of the textbox element, then we call the overridden dispose method to detach the handlers and release resources. The _onKeypress function detects and rejects any non-numeric characters except the backspace character; the _onKeyup handler formats the textbox input by adding comma between every three numbers upon user releasing a key.

Listing 6: Testing the addCommaText control

Figure 3: AddComma Text box screenshot

AddComma Text box screenshot

Summary

So far we have run through some of the very basics about event handling and class creation with ASP .NET AJAX, together with the basic steps for client component development. I hope you are not overwhelmed by the set of new methods, keywords and concepts. Although the Microsoft AJAX library is still very much a work in progress, it has become a powerful tool for developers to create AJAX driven rich websites. And client components are surely an indispensable part of the Microsoft AJAX library, for that it affords us to wrap up nitty- gritty programming details into one black box and reuse it in other applications.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Xun Ding

Web developer, Data Analyst, GIS Programmer

This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Test120Jan
This is my custom article
Top
 
 
 

Discussion


Subject Author Date
placeholder Excellent Article, but... Barry Pekin 10/28/2008 5:07 PM
thanks, but Xun Ding 10/29/2008 11:38 AM

Please login to rate or to leave a comment.