Monday, February 18, 2008

AJAX Basics

When I first posted my first Ajax links on this blog, some of my friends asked me to post more basics of Ajax, so that they can use the link more effectively, so today while surfing web I found very good topic on Ajax Basics originally posted on by Scott Mitchell. I hope this will help.

You can find the download links of Ajax components, samples and other utilities on my previous blog post

Introduction Over the past several years web developers have started using JavaScript to make asynchronous postbacks to the web server that only transmit and receive the necessary data; these techniques are commonly referred to as AJAX. When properly implemented, AJAX-enabled web applications offer a highly interactive user interface whose responsiveness rivals that of desktop applications. Popular web applications like the social networking news site Digg and GMail are prime examples of AJAX techniques in action.

Since AJAX involves many disparate technologies at different layers in the networking stack, implementing AJAX without the use of an AJAX framework is difficult and error-prone. Fortunately, Microsoft has released a free AJAX framework for ASP.NET developers: Microsoft ASP.NET AJAX. This article is the first in a series of articles that examines the ASP.NET AJAX framework. This installment provides an overview of AJAX technologies and looks at getting started with Microsoft's framework. Future installments will focus on specific controls and scenarios. Read on to learn more!

A Brief History of Ajax The client-server model is an architecture that involes two actors: a client and a server. The server passively waits for a request from a client and, upon receiving such a request, processes it and returns a reply. The client is responsible for initiating requests to the server, after which is waits for and then processes the data returned in the response. Web applications are classic examples of the client-server model. The client - a web browser, most often - sends a request to a web server for a particular resource. The resource may be static content like an HTML page or an image that the web server can simply return, or it may be dynamic content like an ASP.NET page that must first be processed on the web server before its generated markup can be sent back. Regardless, the interaction is the same: the client requests a particular resource, and the server returns it, be it the binary content of a JPG image or the HTML of a rendered ASP.NET page.

One drawback of the client-server models is latency. Clients must periodically communicate with the server to update the server with the user's input, or to retrieve the latest data from the server. During these periods, the user must wait while the request/response lifecycle plays out. This delay is most clearly evidenced in ASP.NET applications when a postback occurs. Imagine an eCommerce website that lists products in a grid whose contents can be sorted and paged through. However, stepping to the next page requires a postback to the server in order to retrieve the next page of products. Consequently, moving to the next page introduces a delay in the user experience that can take anywhere from less than a second to several seconds, depending on many factors (the user's Internet connection speed, the network congestion, the server load, the database query duration, and so on).

The main culprit here is that the postback requires that all of the page's form fields be sent back to the server and that the entire web page's content be returned to the browser. This volume of exchanged data is overkill since all that is really needed by the client is information about the next page of products. AJAX mitigates these latency issues by using JavaScript to make asynchronous postbacks to the web server; these postbacks transmit and receive the minimum amount of data necessary to perform the requested operation. For a more thorough background of AJAX, be sure to read Jesse James Garrett's essay where he coined the term "Ajax": Ajax: A New Approach to Web Applications.

There are a number of AJAX frameworks available. Most ASP.NET control vendors offer commercial AJAX implementations, and there are many open source libraries as well. In early 2006 Microsoft released its own AJAX framework, Microsoft ASP.NET AJAX, which is the focus of this article series.

An Overview of Microsoft ASP.NET AJAX Microsoft's ASP.NET AJAX framework was designed to work with ASP.NET 2.0 and future versions; it does not work with ASP.NET version 1.x applications. The ASP.NET AJAX framework will ship with Visual Studio 2008 and ASP.NET version 3.5. ASP.NET 2.0 developers, however, need to download and install the framework from Microsoft's website; the "Getting Started with Microsoft ASP.NET AJAX" section later in this article includes a discussion on installing ASP.NET AJAX in a 2.0 environment.

The ASP.NET AJAX framework consists of client-side and server-side logic. There are a bevy of JavaScript libraries that simplify initiating an asychronous postback and processing the response from the server. The client-side libraries also include classes that mimic the .NET Framework's core classes and data types. The server-side components include ASP.NET controls that, when added to a page, implement various AJAX techniques. One such example is the ScriptManager control, which adds references to the client-side script in the page, so that the browser requesting the ASP.NET page downloads the appropriate JavaScript libraries as well. Consequently, you'll use the ScriptManager on any ASP.NET page where you want to utilize the ASP.NET AJAX framework.

In addition to the ScriptManager control, the ASP.NET AJAX framework includes a handful of other server-side controls, such as the UpdatePanel, the Timer, and the UpdateProgress controls. The UpdatePanel control allows you to define a portion of the page that will be updated by an asynchronous request. In short, it allows you to make partial postbacks rather than a full page postback. This improves the responsiveness of the page in two ways: first, when a partial postback occurs only the data relevant to that UpdatePanel is sent to the server, and only the corresponding data is returned; and, second, the partial page postback does not cause the entire page to be "re-drawn" by the browser, so there's no "flash" that is all too common when making full postbacks.

The UpdatePanel is one of the core pieces of the ASP.NET AJAX framework, and one which we will be examining later on in this article. Once an UpdatePanel has been added to a page, you can add the standard ASP.NET web controls - TextBoxes, Buttons, GridViews, DropDownLists, and so on - and they will automatically take advantage of AJAX techniques. For example, if you have a Button and a TextBox in an UpatePanel and the Button is clicked, a partial postback will occur. The Button's Click event handler will be called on the server-side, as expected, and the value of the TextBox's Text property can be accessed as usual. Moreover, any other Web controls within the same UpdatePanel can have their properties read or assigned and they will be re-rendered and their output updated in the user's browser.

In addition to the base server-side controls (the ScriptManager, UpdatePanel, Timer, and so on), Microsoft offers an additional set of interactive controls via the AJAX Control Toolkit. This toolkit includes ratings controls, sliders, modal popup windows, and so forth.

Getting Started with Microsoft ASP.NET AJAX For ASP.NET 2.0 developers, the first step in working with Microsoft ASP.NET AJAX is to download the AJAX Extensions and, optionally, the AJAX Control Toolkit. (ASP.NET 3.5 developers will already have the ASP.NET AJAX framework installed.)

Note: This article only looks at working with the AJAX Extensions (the core of the framework) and leaves the Control Toolkit for a future installment.

To download the ASP.NET AJAX 1.0 framework, visit this page and click the Download button. The ASP.NET AJAX framework is packaged up as an MSI file. Once you've downloaded the MSI file to your computer, double-click it to install the framework. After downloading and installing the ASP.NET AJAX framework, start Visual Studio and choose to create a New Project. In the New Project dialog box you should see a new project type named "ASP.NET AJAX-Enabled Web Application."

Visual Studio includes a new Project Type named ASP.NET AJAX-Enabled Web Application.

Creating an ASP.NET AJAX-Enabled Web Application creates a new Web Application Project with the System.Web.Extensions assembly added as a reference. The System.Web.Extensions assembly contains the core client- and server-side pieces of Microsoft's ASP.NET AJAX framework. Also, the Toolbox includes an AJAX Extensions category with the core server-side AJAX controls.

Our First ASP.NET AJAX Example: Using the UpdatePanel

The UpdatePanel is useful in situations where you only want a portion of the page to postback rather than the entire page. Such a limited postback is called a partial postback, and is easy to implement using the UpdatePanel. As you know, many ASP.NET controls can cause postbacks: Button controls, when clicked; DropDownLists and CheckBoxes, when their AutoPostBack property is set to True; and so on. Under normal circumstances, when these controls cause a postback, the entire page is posted back. All form field values are sent from the browser to the server. The server then re-renders the entire page and returns the complete HTML, which is then redisplayed by the browser.

When these controls appear in an UpdatePanel, however, a partial page postback is initiated instead. Only the form fields in the UpdatePanel are sent to the server. The server then re-renders the page, but only sends back the markup for those controls in the UpdatePanel. The client-side script that initiated the partial postback receives the partial markup results from the server and seamlessly updates the display in the browser with the returned values. Consequently, the UpdatePanel improves the reponsiveness of a page by reducing the amount of data exchanged between the client and the server and by "redrawing" only the portion of the screen that kicked off the partial page postback.

Let's take a look at the UpdatePanel in action. The following demo, which is downloadable at the end of this article, shows a simple example. The UpdatePanel in the demo includes only two controls: a Label and a Button. The Label Web control displays the text of a randomly selected joke. Clicking the Button loads a new randomly selected joke into the Label. If you are following along at your computer, start by adding a new ASP.NET page to the ASP.NET AJAX-Enabled Web Application we created back in the "Getting Started with Microsoft ASP.NET AJAX" section.

Whenever we use the ASP.NET AJAX framework in a page, we need to start by adding a ScriptManager control, so start by adding a ScriptManager to the page. Next, add an UpdatePanel to the page. Within that UpdatePanel, add a Label control and a Button control. After performing these steps, the declarative markup in your web page should look similar to the following:

<asp:ScriptManager ID="myScriptManager" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="JokeUpdatePanel" runat="server"> <ContentTemplate> <asp:Label ID="JokeText" runat="server" Font-Italic="False" Font-Names="Comic Sans MS" Font-Size="Large"></asp:Label> <br /> <br /> <asp:Button ID="NewJokeButton" runat="server" Text="Show Me a Random Joke!" /> </ContentTemplate> </asp:UpdatePanel>

At this point, all that remains is to write the server-side code. When the page is first loaded we want to set the JokeText Label's Text property to a randomly selected joke; likewise, whenever the NewJokeButton is clicked, we want to refresh the Label's Text property with a new joke.

protected void Page_Load(object sender, EventArgs e) { JokeText.Text = GetRandomJoke(); } protected void NewJokeButton_Click(object sender, EventArgs e) { JokeText.Text = GetRandomJoke(); } private string GetRandomJoke() { // Get a random number Random r = new Random(); switch (r.Next(5)) { case 0: return "Why did the chicken cross the road? To get to the other side!!"; case 1: return "How much do pirates pay for their earrings? A Buccaneer!"; case 2: return "Why did the computer squeak? Because someone stepped on it's mouse!"; case 3: return "What is a golfer's favorite letter? Tee!"; default: return "A child comes home from his first day at school. Mom asks, "What did you learn today?" "Not enough," the kid replies, "I have to go back tomorrow.""; } }

At this point we have a page that will utilize AJAX techniques to make a partial page postback when the Button in the UpdatePanel is clicked. Consequently, clicking the "Show Me a Random Joke!" button displays a new joke promptly without having the entire page refresh. Granted, this is an overly simple example since the page already is very lightweight, but this concept can be extended to more real-world scenarios (and will be, in future installments of this article series). For example, you might have a page that has several grids on it showing a plethora of data. You could place each grid in its own UpdatePanel. That way, when a user sorted or paged a grid, a partial postback would occur and the particular grid could be paged or sorted without requiring a full postback.

The takeaway here is that implementing AJAX techniques in an ASP.NET application using the ASP.NET AJAX framework is remarkably easy. The ScriptManager and UpdatePanel controls automatically handle all of the complexities involved with initiating the asynchronous postback and displaying the returned data.

Looking Forward... This article only looked at a simple UpdatePanel example. In real-world scenarios, however, things aren't always as simple. For example, we might want to have some event external to the UpdatePanel trigger a partial postback. We've not yet looked at working directly with the client-side AJAX libraries; nor have we explored the wealth of controls in the AJAX Control Toolkit. These, and many more topics, You can find the download links of Ajax components, samples and other utilities on my previous blog post

Happy Programming!

By Scott Mitchell


Post a Comment