Chapter 23. Building More Responsive Web Pages with ASP.NET AJAX

<feature><title></title>

In this hour, we will cover

  • The benefits of AJAX-enabled websites

  • How AJAX improves the responsiveness of web pages

  • Implementing AJAX with the UpdatePanel control

  • Using Multiple UpdatePanels on an ASP.NET page

  • Displaying a Loading message with the UpdateProgress control

</feature>

Throughout this book we have created many ASP.NET pages that execute server-side code based on some user action. Clicking a button causes the Button Web control’s server-side Click event handler to execute. Selecting an item from a DropDownList control whose AutoPostBack property is set to True causes the DropDownList’s SelectedIndexChanged event to fire. Clicking the header column of a GridView that is configured to enable sorting sorts the grid by that column.

For server-side code to execute in response to a client-side action, the client must communicate with the web server. As we saw in Hour 9, “Web Form Basics,” this is commonly performed through the HTML <form> element. When a postback form is submitted—be it through the user clicking a submit button or client-side JavaScript initiating the submission—the browser rerequests the same page from the web server, sending along the names and values of the form’s <input> elements. The web server processes the request and then retransmits the entire page’s HTML back to the browser, which redisplays it.

Submitting a form and redisplaying the resulting HTML is costly in terms of performance. Even with a high-speed Internet connection, this interaction may take several seconds to complete, depending on how many <input> elements are in the form, the length of the <input> elements’ values, and the size of the retransmitted HTML. This workflow can be greatly enhanced by using AJAX, a set of technologies offering a more streamlined approach to transferring data between the browser and web server. In this hour we discuss the benefits of AJAX and see how to create AJAX-enabled ASP.NET pages.

An Overview of AJAX

A traditional Web Form postback involves the web browser sending all the form’s <input> elements’ names and values to the web server and the web server returning the entire HTML for the page. For example, imagine that you were designing a page that had two sortable GridView controls on the page showing data from two different database tables. Using the techniques we’ve examined throughout this book, if the user clicked one of the first GridView’s sort links the page would be posted back. On postback, the ASP.NET page would reretrieve the data for the first GridView, sort it by the specified column, and rebind it to the grid. Then the page’s entire HTML would be returned to the browser and redisplayed. The net effect, from the end user’s perspective, is that she clicked on a sort link and, after a delay of a second or two, the page was redisplayed with the grid’s data sorted by the specified column.

This approach is inefficient because much of the data exchanged between the browser and the web server is superfluous. Most notably, the web server returns the entire page’s rendered HTML to the browser, even though the only modified HTML is for the GridView that was just sorted. The rest of the page’s HTML—including the HTML for the second GridView—was needlessly rerendered by the ASP.NET engine and returned to the browser.

AJAX is a set of interrelated technologies that improves this data exchange by transmitting only the necessary <input> element names and values and returning only the HTML portions of the page that need to be updated.

By the Way

Because AJAX submits a subset of <input> elements and receives only a portion of the page’s rendered HTML, an AJAX-enabled postback is referred to as a partial page postback, or simply a partial postback.

The workflow of a partial page postback is depicted in Figure 23.1.

A partial page postback transmits only a subset of the <input> elements and rendered HTML.

Figure 23.1. A partial page postback transmits only a subset of the <input> elements and rendered HTML.

Because less information is shuttled between the browser and web server, and because the browser dynamically updates only those portions of the page that have changed, the user’s browser display is updated more quickly when using an AJAX-enabled page. Furthermore, the browser is able to seamlessly update the modified regions and avoid the page flash that is sometimes present when redisplaying the HTML from a full postback. The net result of AJAX’s reduced transmission payload is a page that is much more responsive than one using traditional full postbacks.

By the Way

More and more websites are using AJAX to improve the user experience. Two great examples of AJAX-enabled user interfaces are Google’s Gmail service (www.gmail.com) and the Google Suggest search page (www.google.com/webhp?complete=1&hl=en). Gmail employs AJAX to load selected email messages in the window without a full postback. Google Suggest prompts visitors for a search term. As you type in the search term, suggested searches are dynamically displayed in a drop-down list, along with how many results exist in Google’s database.

A Look at the Technologies Involved

As you may have guessed, building an AJAX-enabled web page requires added functionality to both the web browser and web server. As Figure 23.1 illustrates, the web browser must know how to make a partial postback (Step 1), the web server must know how to partially render the page and return only the necessary HTML back to the browser (Step 2), and the browser must be able to update its display to integrate the returned HTML (Step 3).

The browser works its magic through the use of client-side JavaScript. JavaScript is a powerful scripting language whose code is supplied by the web server, but is executed on the user’s computer. JavaScript includes functions for sending information to a web server, and these functions are used to initiate the partial page postback. Moreover, JavaScript can dynamically update the contents and structure of the web page displayed in the browser. These features are used to render the partial HTML returned by the web server.

By the Way

We’ve already utilized JavaScript in previous examples. For example, setting the DropDownList control’s AutoPostBack property to True causes the ASP.NET engine to inject a JavaScript that automatically submits the Web Form when the user changes her drop-down list selection.

On the web server side, ASP.NET includes the capability to selectively render and return the markup for a portion of the page.

At this point it’s only natural to feel a bit overwhelmed. We’ve talked sparingly about JavaScript, and this is the first mention of ASP.NET’s ability to partially render a page. The good news is that we won’t be responsible for writing JavaScript code or handling the partial rendering logic. That task falls to ASP.NET AJAX framework, which is a rich AJAX library created by Microsoft and built into ASP.NET version 3.5.

With the ASP.NET AJAX framework, utilizing AJAX techniques is as easy as dragging and dropping.

Using the ASP.NET AJAX Framework

The ASP.NET AJAX framework includes a handful of Web controls. The most important ones are

  • ScriptManager—Provides the necessary JavaScript functionality for performing partial postbacks and updating the browser’s display.

  • UpdatePanel—Defines a region on the page that can participate in a partial postback.

  • UpdateProgress—Displays content during the partial postback; this control is useful in providing users feedback that their request is being processed.

The ScriptManager control handles the complex communications between the visitor’s browser and the web server, and must appear on every ASP.NET page that uses the ASP.NET AJAX framework. To use the UpdatePanel on a page, for example, you must also include a ScriptManager control.

Did you Know?

If you are building a website using master pages where the majority of the ASP.NET pages are AJAX enabled, it makes sense to place the ScriptManager in the master page so that it is automatically included in each content page. In fact, when adding a new item to a website through Visual Web Developer, one of the options is to add an AJAX Master Page. If you select this option, Visual Web Developer creates a master page that includes a ScriptManager control.

The UpdatePanel control defines a region on the page that can participate in a partial postback. As we will see shortly, after an UpdatePanel has been added to the page, additional Web controls may be added within the UpdatePanel. When the user visiting the page interacts with one of these controls in a manner that would normally cause a full page postback—such as clicking a submit button—a partial page postback occurs instead. The UpdatePanel, along with JavaScript routines added by the ScriptManager control, automatically handles all the AJAX-related tasks: initiating the partial page postback from the browser, performing the partial page rendering on the web server, and updating the browser’s display with the returned markup.

When a user clicks a submit button in a web page using full page postbacks, the browser indicates that a postback is occurring by displaying a progress bar and providing other visual feedback. But during a partial page postback, the browser itself does not provide any visual feedback. The UpdateProgress control is useful for informing the user that a partial page postback is in progress. For example, you could configure the UpdateProgress control to display a message titled Loading... please wait. We examine the UpdateProgress control in the “Displaying a Progress Message for Long-Running Partial Postbacks” section.

Working with the UpdatePanel Control

To demonstrate the principals behind AJAX, as well as how to use the UpdatePanel control to add AJAX functionality to an ASP.NET web page, create an ASP.NET page named AJAXSimple.aspx. Add a Label Web control to the page named CurrentTime and clear out its Text property. Beneath the Label, add a Button Web control and set its ID and Text properties to FullPostBackButton and Full Postback, respectively.

Next, create an event handler for the page’s Load event and write code that sets the CurrentTime Label’s Text property to the current date and time.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    CurrentTime.Text = DateTime.Now
End Sub

With this code in place, visit the page through a browser. When the page is first loaded, you should see the current date and time displayed. Each time the button is clicked, the page performs a full postback, the Page_Load event executes, and the displayed date and time are updated.

Return to Visual Web Developer and add an UpdatePanel control to the page below the existing Label and Button controls. The UpdatePanel is located in the AJAX Extensions portion of the Toolbox. We also need to add a ScriptManager control to the page. A page can have at most one ScriptManager control and the ScriptManager must appear before any UpdatePanel controls.

At this point your screen should look similar to Figure 23.2.

A partial page postback transmits only a subset of the <input> elements and rendered HTML.

Figure 23.2. A partial page postback transmits only a subset of the <input> elements and rendered HTML.

Watch Out!

If you forget to add the ScriptManager control, or locate it below any UpdatePanel controls on the page, an error message is displayed when the page is viewed through the browser. The error message is pretty self-explanatory: The control with ID UpdatePanelID requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it.

Next, add another Label Web control and another Button Web control to the page, but this time, add them within the UpdatePanel. To accomplish this, switch to the Design view and then drag the Label and Button from the Toolbox and drop them within the UpdatePanel. Set the Label’s ID property to CurrentTimeAJAX and clear out its Text property; set the Button’s ID and Text properties to PartialPostBackButton and Partial Postback, respectively.

We now need to update the page’s code so that the CurrentTimeAJAX Label’s Text property is also assigned the current date and time on page load. To accomplish this, update the Page_Load event handler as follows:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    CurrentTime.Text = DateTime.Now
    CurrentTimeAJAX.Text = DateTime.Now
End Sub

With this code in place, visit the page through a browser. Both Label controls should display the same date and time value (see Figure 23.3). However, clicking the Partial Postback button only updates the date and time value displayed by the CurrentTimeAJAX Label (see Figure 23.4). Now click the Full Postback button. The Label controls are back in synchrony, displaying the same value. What’s going on here?

The two Label controls display the same date and time value.

Figure 23.3. The two Label controls display the same date and time value.

The two Labels values differ.

Figure 23.4. The two Labels values differ.

When the page is first visited or whenever the Full Postback button is clicked, the entire page is rerendered and redisplayed in the browser. However, when the Partial Postback button is clicked, a partial postback ensues. The web server only renders the markup for the controls within the UpdatePanel, and only this markup is returned to the browser. Consequently, only the content within the UpdatePanel—the CurrentTimeAJAX Label—is refreshed.

The UpdatePanel control defines a region within which user actions that would normally cause a full page postback instead trigger a partial page postback. When a partial postback occurs, the web server refreshes only the contents of the UpdatePanel; areas outside the UpdatePanel are not updated. A full page postback, however, refreshes the entire contents of the page, including the content within UpdatePanel controls.

By the Way

As noted earlier, the key benefit of AJAX is that it produces a more responsive user experience because the interaction between the client and the server is much quicker with AJAX than when using full page postback. However, you may not have noticed any difference in speed between the full postback and partial postback in the current date and time example.

One of the main bottlenecks in a web application is the time it takes to transfer data between your computer and the web server. AJAX improves the responsiveness of a page by reducing the amount of data exchanged. But when testing an ASP.NET application locally, this bottleneck is a nonissue. In short, the speed benefits of AJAX are best seen when visiting a remote website. We’ll look at how to move your web application to a web hosting company in the next hour, “Deploying Your Website.”

Using Multiple UpdatePanel Controls

An ASP.NET page may contain multiple UpdatePanels. This is useful if you have multiple regions on the screen whose content is updated independently. Consider a web page with two sortable GridView controls on the page, showing different data. With full page postbacks, sorting one grid causes the entire page to reload, but this is a waste of bandwidth because only the contents of one grid have changed. Such a page is a prime candidate for using two UpdatePanel controls—one for each GridView control on the page.

Create a new page named MultipleUpdatePanels.aspx. Start by adding a ScriptManager control at the top of the Web Form. Next, add two UpdatePanel controls. Then add a SqlDataSource control to the first UpdatePanel. Name the SqlDataSource BooksDataSource and configure it to return the BookID and Title columns from the Books table. Next, add a GridView to the same UpdatePanel, set its ID to BooksGrid, and bind it to the BooksDataSource control. Repeat these steps in the second UpdatePanel, but this time name the SqlDataSource control GenreDataSource and have it return the distinct Genre values from the Books table. Name the GridView GenreGrid and bind it to the GenreDataSource. Enable sorting for both GridViews.

Next, add three Label controls to the page, clearing out the Text properties for all three. Place one Label outside the UpdatePanel controls and name it CurrentTime; put another one inside the first UpdatePanel and name it CurrentTimeAJAX1; put the third Label inside the other UpdatePanel, setting its ID to CurrentTimeAJAX2. Create the Page_Load event handler and set each Label’s Text property to the current date and time.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    CurrentTime.Text = DateTime.Now
    CurrentTimeAJAX1.Text = DateTime.Now
    CurrentTimeAJAX2.Text = DateTime.Now
End Sub

Add a Button Web control outside of the UpdatePanels. Set its ID and Text properties to FullPostbackButton and Full Postback, respectively.

After adding these controls, your screen should look similar to Figure 23.5.

Two sortable GridViews have been added to two UpdatePanels.

Figure 23.5. Two sortable GridViews have been added to two UpdatePanels.

Visit the page through a browser. Each Label control displays the date and time that the portion was last refreshed. When the page is first visited, or whenever the Full Postback button is clicked, all Labels should show the same value. Clicking one of the sort links in either GridView causes a partial postback. As you may have expected, sorting either of the grids leaves the CurrentTime Label outside of the UpdatePanels unaffected. What you might not have expected, though, is that both UpdatePanels are updated when either grid is sorted, as evidenced by the fact that both UpdatePanels’ Label controls show the same date and time value (see Figure 23.6).

Sorting either GridView updates both UpdatePanels.

Figure 23.6. Sorting either GridView updates both UpdatePanels.

By default, when any UpdatePanel on the page instigates a partial postback, all the UpdatePanels’ displays are updated. In this example, the contents in the two UpdatePanels are independent, so when a partial postback is instigated from one UpdatePanel there’s no need to update the other’s contents. To instruct an UpdatePanel to update its contents only when it triggers a partial postback, change its UpdateMode property from Always (the default) to Conditional.

After setting both UpdatePanels’ UpdateMode properties to Conditional, revisit the page. This time, sorting a grid updates only the contents of the grid’s UpdatePanel. Figure 23.7 shows the results of sorting the BooksGrid by Title. Note the discrepancy between the two UpdatePanels’ Labels, indicating that the sort operation in the first UpdatePanel did not also refresh the content of the second UpdatePanel.

Now only the UpdatePanel that triggered the partial postback is refreshed.

Figure 23.7. Now only the UpdatePanel that triggered the partial postback is refreshed.

Did you Know?

The UpdatePanel control can be configured to refresh based on a user action elsewhere in the page. For example, you can add a Button to the page that, when clicked, performs a partial postback and causes a specific UpdatePanel to refresh. For more information on additional means for triggering an UpdatePanel to refresh, read “Using the UpdatePanel” at http://aspnet.4guysfromrolla.com/articles/102407-1.aspx.

Displaying a Progress Message for Long-Running Partial Postbacks

Ideally, all requests to the web server will be quickly handled and the resulting markup speedily returned to the requesting browser. But sometimes it may take several seconds for the communication between the browser and the web server to complete, even when using AJAX techniques. There are many potential causes for such a slowdown. Real-world projects usually involve querying large databases or require complex database queries that may take several seconds to complete. The web server may be under an unusually high load if there is a sudden spike of traffic. And delays are commonplace for users who have a slow connection to the Internet.

Regardless of the reasons behind a slow serving page, it helps to provide users with visual feedback so that they know their request is being processed. Displaying such feedback during a partial page postback is easy, thanks to the UpdateProgress control. The UpdateProgress control displays its contents for a particular UpdatePanel after a specified number of milliseconds have elapsed.

To see the benefits of the UpdateProgress control, we need to first devise a long-running scenario. Right now, the partial page postbacks return so quickly that the UpdateProgress control does not have time to display feedback. However, we can write code that introduces an artificial delay.

Start by creating an ASP.NET page named UpdateProgress.aspx. Add a ScriptManager to the page followed by an UpdatePanel. In the UpdatePanel, add a Label and a Button control. Set the Label control’s ID property to StatusMessage and clear out its Text property. Set the Button’s ID and Text properties to SlowOperationButton and Start Slow Operation, respectively.

Create an event handler for this Button’s Click event and add the following code:

Protected Sub SlowOperationButton_Click(ByVal sender As Object, ByVal e As  System.EventArgs) Handles SlowOperationButton.Click
    'Pause for 5 seconds
    System.Threading.Thread.Sleep(5000)

    StatusMessage.Text = "Slow operation complete! The current time is: "  & DateTime.Now
End Sub

The statement System.Threading.Thread.Sleep(5000) pauses the processing of this page for 5,000 milliseconds, or 5 seconds. It then sets the StatusMessage Label’s Text property to the current date and time.

Visit this page through a browser and click the Start Slow Operation button. This causes a partial postback that will take 5 seconds to complete. During that time, there is no feedback as to what’s happening. A confused user may click the button again, thinking that the first click did not register somehow. After 5 seconds, the StatusMessage Label indicates that the slow running operation has completed.

Let’s update this page to include feedback that the partial page postback is in progress. Add an UpdateProgress control to the page. Add whatever markup you want to display during the partial postback within the UpdateProgress control. You can enter text, drag on a Label Web control, or add an Image Web control. For this example, add a Label control into the UpdateProgress control and set its Text property to Loading.... Feel free to also set any of the Label’s formatting properties.

The UpdateProgress control has two properties of interest:

  • AssociatedUpdatePanelIDSet this property to the ID of a UpdatePanel control. When this UpdatePanel instigates a partial postback, the UpdateProgress control’s contents are displayed.

  • DisplayAfterSpecifies a delay, in milliseconds, between when the partial postback begins and when the UpdateProgress’s contents are displayed. This property defaults to 500, or 0.5 seconds. It is useful to prevent the UpdateProgress from displaying for partial postbacks that complete very quickly.

Set the UpdateProgress’s AssociatedUpdatePanelID to the ID of the UpdatePanel on the page and then revisit the page through a browser. This time when the Start Slow Operation button is clicked, the Loading... message appears and remains until the partial postback completes (see Figure 23.8).

The Loading... message appears during the partial postback.

Figure 23.8. The Loading... message appears during the partial postback.

Did you Know?

Many websites use a small animated image file, such as a rotating circle, to inform users that their request is being processed. To create an AJAX loading image for your site, check out www.ajaxload.info. You can specify the style of animation and the foreground and background colors, and this neat website generates a free AJAX loading image based on your settings.

Summary

AJAX is a set of complementary web technologies that work together to provide a more responsive web interface. This goal is accomplished by reducing the amount of information typically exchanged in a full page postback by selectively posting back, rendering, and updating the display for the affected regions of the page.

Although communications and workflow between the client and server in an AJAX-enabled application is complex, the ASP.NET AJAX framework makes building such applications as easy as dragging and dropping. The key components of the framework are the ScriptManager and UpdatePanel controls. The ScriptManager provides the necessary client-side JavaScript, whereas the UpdatePanel defines a region on the screen that can participate in partial page postbacks. In addition to these controls, there’s the UpdateProgress control, which is useful for displaying a progress message during a partial postback.

Many websites today use AJAX to offer a more responsive user interface. As AJAX has matured, it has become easier to build AJAX-enabled web pages. I encourage you to explore the ASP.NET AJAX framework in more depth. Two great resources are the suite of AJAX tutorials and training videos, available online at www.asp.net/learn/ajax and www.asp.net/learn/ajax-videos.

Q&A

Q.

It sounds like AJAX uses a lot of advanced JavaScript techniques. Are there any browsers that Microsoft’s ASP.NET AJAX framework will not work with?

A.

AJAX does rely heavily on JavaScript, so the UpdatePanel and other ASP.NET AJAX framework features may not work when visited by older browsers or browsers that have disabled JavaScript support. Microsoft’s ASP.NET AJAX framework works with the following browsers:

  • Microsoft Internet Explorer 6.0 and later

  • Mozilla FireFox version 1.5 and later

  • Opera version 9.0 and later

  • Apple Safari version 2.0 and later

Q.

I know that the UpdatePanel can be used in tandem with the standard ASP.NET Web controls to provide an AJAX-enabled web page. Do any ASP.NET controls designed specifically to use AJAX techniques exist?

A.

Microsoft offers a rich suite of AJAX controls in its ASP.NET AJAX Control Toolkit. This toolkit includes controls such as an AJAX-enabled Calendar, a content rating control, a slider, a filtered text box, and many others. Unfortunately, this toolkit is not yet built in to ASP.NET like the core ASP.NET AJAX framework and its Web controls—ScriptManager, UpdatePanel, and UpdateProgress. Perhaps future versions of ASP.NET will include the AJAX Control Toolkit controls by default.

To download the ASP.NET AJAX Control Toolkit, visit www.asp.net/ajax/ajaxcontroltoolkit. You’ll find a plethora of live demos and examples online at www.asp.net/ajax/ajaxcontroltoolkit/samples.

Workshop

Quiz

1.

Why do AJAX-enabled web applications offer a more responsive user interface than traditional web applications?

2.

How does a partial page postback differ from a full page postback?

3.

True or False: JavaScript is an essential part of any AJAX-enabled website.

4.

What ASP.NET AJAX framework control must be added to all AJAX-enabled web pages? What happens if you forget to add this control?

5.

True or False: You cannot have more than one UpdatePanel control on an ASP.NET page.

6.

What is the purpose of the UpdateProgress control?

Answers

1.

Because AJAX techniques streamline the data exchanged between the browser and web server, partial page postbacks are faster than full page postbacks.

2.

In a full page postback, all the form’s <input> elements’ names and values are sent to the web server, and the entire page’s markup is rendered and returned to the browser. In a partial page postback, the browser transmits only the necessary <input> fields to the web server. The web server then renders and returns the markup for just the application portion of the page. The browser then updates its display using the HTML returned from the browser. Refer to Figure 23.1 for a more detailed look at the steps that compose a partial postback.

3.

True.

4.

The ScriptManager control. If you omit this essential control, the ASP.NET engine displays an error message when the page is visited through a browser.

5.

False. You can have any number of UpdatePanel controls on a page.

6.

The UpdateProgress control displays its content during a specified UpdatePanel control’s partial postback. It provides visual feedback that the user’s requested action is being processed.

Exercises

1.

Create an ASP.NET page and add ScriptManager and UpdatePanel controls. Next, add a SqlDataSource and DetailsView control within the UpdatePanel and configure them so that the visitor can add new records to the Books table. If you need to brush up on inserting data into a database using the DetailsView control, return to Hour 16, “Deleting, Inserting, and Editing Data.”

Like the examples in this hour, add two Label Web controls to this page—one outside the UpdatePanel and the other within the UpdatePanel. Have the Label Text properties assigned to the current date and time on each page load. When testing the page, note that when the page is first visited, the two Labels’ values match, but when a new record is added through the DetailsView control, the Label within the UpdatePanel is updated, but one outside the UpdatePanel is not.

2.

Extend the page created in the first exercise by adding a second UpdatePanel control. Drag a GridView control into this second UpdatePanel and bind it to the same SqlDataSource control used by the DetailsView. Also add a Label Web control to this second UpdatePanel and configure it to display the current date and time on each page visit. What happens when a new record is added through the DetailsView control? What happens if you set the two UpdatePanels’ UpdateMode properties to Conditional? Try to figure out how to add a trigger to the second UpdatePanel so that it is updated only when a new record is added via the DetailsView control.

 

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

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