Chapter 5. Using AJAX for Rich Web Pages

In This Chapter

  • Discovering what AJAX does and why you should consider using it

  • Using AJAX extensions to create rich Web Applications

  • Extending ASP.NET controls with AJAX for smooth page response

  • Creating custom AJAX controls for additional functionality

Creating Web pages with rich content while also creating Web pages with nimble response is the Holy Grail of Web development. For years, desktop applications have performed user interface (UI) operations with almost no perceptible delay, but Web applications are at the mercy of the Internet connection speed. Even with a fast Internet connection, though, many Web applications with rich content are sluggish, taking as long as several seconds to load.

This chapter offers a solution: the addition of Asynchronous JavaScript and XML (AJAX) extensions. These extensions go beyond the traditional ASP.NET controls and give you the ability to make your Web pages respond almost as well as desktop applications, even if the content is relatively rich.

AJAX Explained: What It Does and Why You Should Consider Using It

AJAX is a relatively new technology that relies on JavaScript. The JavaScript code that AJAX employs allows it to perform to the point where very little perceptible delay is seen with the UI because AJAX reduces the amount of data that must be transferred from the server to the client. As a result, the user experience is far more enjoyable because users don't wait for page updates and refreshes.

ASP.NET postback architecture

Start with a little background on the ASP.NET postback architecture. Say that you create an ASP.NET Web application that has two text fields: a button and a label. Here's what happens:

  1. The text fields allow users to enter the width and a height of a rectangle.

  2. The button calculates the area of the rectangle.

  3. The area is placed into the label showing the result of the calculation.

If this Web application were a desktop application, the architecture would be trivial. The program code would simply get the values, do the calculation, and then display the result. However, ASP.NET controls execute on the server and not on the client machine. As a result, the page needs to present its data to the server so that the server can do the calculation, populate the label with the result, and serve up the new page. The process of controls executing on the server and returning data to the client is commonly known as a postback.

When Microsoft introduced this technology in 2000, developers weren't crazy about it. Postbacks put more load on servers because the calculation and result display require a round trip to the server. Developers soon realized, though, how easy they made Web application development, so the postback architecture won the day.

Unfortunately, though, the round trip to the server causes a delay. Although a desktop application does this trip with no real delay, a Web application may give a noticeable delay during heavy traffic. So, although the ASP.NET postback architecture is brilliant for easy and robust Web development, AJAX, a way to get rid of the page roundtrip delays, was developed.

Partial page updates

You can just about solve the postback delay issue if your applications can simply update the portion of the page that needs to be updated. Easy, right? People have been trying to solve that problem for years with IFrames and other technologies. None, though, have worked nearly as well as AJAX, which is built on JavaScript technology.

AJAX allows Web applications to perform partial page updates. Only the page elements that need to be updated are, thus providing a far more responsive page refresh mechanism. And if a Web application developer is judicious in how pages are designed, almost no perceptible refresh delay is noticed.

AJAX uses JavaScript to perform partial page updates. This section gives a short description of the mechanism.

How JavaScript interacts in HTML documents

First, make sure that you know that JavaScript isn't Java. Java is compiled binary code that can reside on the Internet as applets. These applets are loaded and executed via the Java Virtual Machine (JVM).

Comparatively, JavaScript can be part of an HTML page. It can technically be a separate file that's referenced in an HTML page, but the browser treats it as if the referenced code is part of the HTML where it's referenced.

The browser interprets JavaScript code. Interpreted code isn't as fast as compiled code, but modern-day browsers and fast machines easily handle the interpretation so that users don't notice.

JavaScript has been used for many years in a technique known as Dynamic HTML (DHTML), which is a way of making HTML more dynamic by allowing the client machine to act on HTML elements. For example, DHTML code can cause a test string to turn green when the mouse hovers over it and then back to black when the mouse leaves its area.

Here's a simple JavaScript page that changes the color of a text string when the mouse hovers over it:

<html>
<body>
<h1>This page demonstrates DHTML.</h1>
<span id="Test"
 onMouseOver="this.style.color='green'"
 onMouseOut="this.style.color='black'">
   Hi there, hover over me.</span>
</body>
</html>

If you're unsure how to work with JavaScript, you can check out this tutorial:

www.w3schools.com/js/default.asp

Using the JavaScript HttpRequest mechanism

DHTML isn't enough to do partial page updates. You still need a way to make a request from the server. The mechanism that's used for this is an HTTP request, performed by the JavaScript XMLHttpRequest object.

With an HTTP request, a Web page can make a request to — and get a response from — a Web server without reloading the page. The user will stay on the same page, not noticing that scripts might request pages or send data to a server in the background.

Listing 5-1 performs a simple fetch of a document via an HTTP request that relies on the XMLHttpRequest object.

Example 5-1. Simple Document Fetch Using XMLHttpRequest

<script language="JavaScript">

var XMLHttp;

function LoadData(url)
{

     XMLHttp = null;

     // code for Firefoxetc.
     if( window.XMLHttpRequest )
     {
          XMLHttp= new XMLHttpRequest();
     }

     // code for Internet Explorer
     else if( window.ActiveXObject )
     {
          XMLHttp= new ActiveXObject( "Microsoft.XMLHTTP" );
     }

     if( xmlhttp != null )
     {
          XMLHttp.onreadystatechange = state_Change;
          XMLHttp.open( "GET", url, true );
          XMLHttp.send( null );
     }
     else
     {
          alert( "Your browser does not support XMLHTTP." );
     }

}
</script>

Fortunately, you never need to do this kind of JavaScript coding. The AJAX extensions do it all for you. The AJAX controls inject the appropriate JavaScript code into the HTML output stream without you needing to code any JavaScript yourself.

Using the XML Data that is returned

The data that's returned is in XML format. XML is simply a way of representing data. It's done with tags, the same way that HTML is done, except that XML allows you to create your own tags that best describe and represent your data.

Here again, you may be worried about handling the XML. Converting simple XML to non-XML data isn't hard, but it's an extra step that can complicate things. Fortunately, the AJAX controls handle all this conversion for you. Instead of actually getting XML, your controls give you simple data types, such as strings and integers.

Using AJAX Extensions

AJAX extensions are included in Visual Studio 2010. In Visual Studio 2005, you had to download and install them, but these extensions are part of the Visual Studio 2010 installation. You can find the AJAX extensions in the toolbox, in the section labeled AJAX Extensions, as shown in Figure 5-1.

The AJAX extensions are in the toolbox.

Figure 5-1. The AJAX extensions are in the toolbox.

Creating your first AJAX Web application

Get started with AJAX by creating your first AJAX Web site. To create a new AJAX-enabled Web site, follow these steps:

  1. Choose File

    Creating your first AJAX Web application

    The New Web Site dialog box appears.

  2. Click the ASP.NET Web Site template.

  3. Select the language from the Language drop-down list.

  4. Choose HTTP for the location for the new Web site. Enter a name, such as FirstAJAXWebsite, after the pathname, as shown in Figure 5-2.

    Name the Web site.

    Figure 5-2. Name the Web site.

  5. Click OK to create the ASP.NET Web site.

    The default.aspx page opens in Split view.

  6. From the AJAX Extensions tab of the toolbox, place one — and only one — ScriptManager object into the form in the Design view.

That's all you need to do to create an AJAX-enabled Web site. Continue to explore how Ajax sites work by adapting and modifying this basic application in the sections that follow.

Adding traditional ASP.NET controls to the form

Controls in a Web site are similar to controls in applications that you create in Visual Studio — the buttons, boxes, and so on that users interact with on-screen. The easiest way to figure out how they work is to experiment with them. Using the site you created in the preceding section, you can start by adding three labels and a button to the site. These are traditional ASP.NET controls. Get these controls working and take a look at this simple application first, though, before going on to implement a partial page update pattern.

To add the ASP.NET server controls, follow these steps:

  1. Add three labels and a button to the form.

  2. Double-click the button to create an event that causes a postback.

  3. Double-click the page and create a Page_Load event handler.

  4. Add this code to the Page_Load method:

    • VB

      Label1.Text = Date.Now
      Label2.Text = Date.Now
      Label3.Text = Date.Now
    • C#

      Label1.Text = DateTime.Now.ToString();
      Label2.Text = DateTime.Now.ToString();
      Label3.Text = DateTime.Now.ToString();
  5. Run the program by pressing Ctrl+F5.

    You see the labels reflect the time of the last postback, as shown in Figure 5-3. The button causes postbacks and subsequent time changes.

The labels on the form show the current date and time.

Figure 5-3. The labels on the form show the current date and time.

Using AJAX to implement a partial page update pattern

After you have an ASP.NET application working, use AJAX to implement a partial page-update pattern. Working from the site created in the preceding section, the end result is that the button causes an update for the second label only.

To implement the partial page update pattern, follow these steps:

  1. From the AJAX Extensions tab of the toolbox, add an UpdatePanel control above the second label.

  2. Drag the second label into the UpdatePanel control.

  3. Drag the button into the UpdatePanel control.

  4. Run the program by pressing Ctrl+F5.

    You see the labels reflect the time of the first page load. Then, only the second label is updated in response to a button click, as shown in Figure 5-4.

The button causes an update in the second label only.

Figure 5-4. The button causes an update in the second label only.

Updating controls outside UpdatePanel

Sometimes, you need to do partial page updates when the control that fires off the update can't be inside UpdatePanel. Modify your application from preceding sections once again and take the button out of UpdatePanel. Then, add a Triggers collection to UpdatePanel. A Triggers collection manages the AJAX events that fire off in response to UI events. In the Triggers collection, specify that the second label should be updated by the button, even though the button is outside UpdatePanel.

To implement the Triggers collection and have a button outside UpdatePanel cause an update, follow these steps:

  1. From the FirstAJAXWebSite that you're working with, move the button from inside UpdatePanel to the bottom of the page so that it's no longer inside UpdatePanel.

  2. Open the Properties window for UpdatePanel.

  3. Click the ellipsis button beside the Triggers property.

    The Collection Editor dialog box appears, as shown in Figure 5-5.

    The Collection Editor allows you to add a trigger.

    Figure 5-5. The Collection Editor allows you to add a trigger.

  4. Click the Add button.

    An AsynPostBack member is added.

  5. In the right side of the editor, set the controlID to Button1 and the EventName to Click.

    This step wires up the buttons Click event to the UpdatePanel update so that the Click event fires off an event trigger that connects it to UpdatePanel.

  6. Click Add.

    An AsynPostBack member is added.

  7. Run the program by pressing Ctrl+F5.

    The labels reflect the time of the first page load. Then, only the second label is updated in response to a button click, even though it's no longer in UpdatePanel, as shown in Figure 5-6.

The button causes an update only in the second label.

Figure 5-6. The button causes an update only in the second label.

Using the AJAX Controls

There's more to AJAX than the extensions. A rich set of controls is provided in the AJAX Control Toolkit, which you can download from www.asp.net. At this Web site, click the AJAX button, click the Download button, and then follow the links to download the latest AJAX Control Toolkit.

The Toolkit is contained inside a Zip archive, so extract it to your hard drive. For this explanation, use this extraction path:

C:Userslux mundiDocumentsVisual Studio 2010 Desk Reference
    AjaxControlToolkitBinary

Adding the AJAX Control Toolkit to the Visual Studio toolbox

Before using the AJAX Control Toolkit, you need to add a reference to the Visual Studio toolbox. This reference makes dragging controls to the Web application's form easy.

To add the AJAX Control Toolkit to the Visual Studio toolbox, follow these steps:

  1. Open the Visual Studio toolbox.

  2. Right-click and choose Add Tab.

  3. Open the Properties window for UpdatePanel.

  4. Name the tab AJAX Toolkit.

  5. Right-click the newly created tab and choose Choose Items.

  6. Click the Browse button and navigate to the file at

    C:Userslux mundiDocumentsVisual Studio 2010 Desk Reference
        AjaxControlToolkitBinaryAjaxControlToolkit.dll

    You see many controls appear in the AJAX Toolkit tab, as shown in Figure 5-7.

The AJAX Toolkit has many controls.

Figure 5-7. The AJAX Toolkit has many controls.

Using AJAX controls from the Toolkit

After you have the AJAX Toolkit installed and set up, as explained in the preceding section, you can get started using the controls. Begin by using a ConfirmButtonExtender. The control gives you the ability to confirm actions in response to user button clicks.

To use a ConfirmButtonExtender, follow these steps:

  1. Drag a ConfirmButtonExtender control from the AJAX Toolkit tab area of the toolbox onto the form right above the button.

  2. Open the ConfirmButtonExtender properties.

  3. Choose Button1 as the TargetControlID.

  4. Enter some text into the ConfirmText property.

    For example, enter Do you want to update the second label?

  5. Run the program by pressing Ctrl+F5.

    When you click the button, you get a confirmation alert, as shown in Figure 5-8.

    This AJAX control confirms a button action.

    Figure 5-8. This AJAX control confirms a button action.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156