31. Using ASP.NET Ajax

What Is Ajax?

The underlying architecture of web applications has always posed a problem with usability. Whenever a user performs an action on a page that requires a postback to the web server, data from all form fields is sent over the network, the page goes blank, and the browser sits in limbo waiting for the web server to send the response. In a typical ASP.NET scenario where a postback reloads the same page after the server processes the data, the speed of the application can be sacrificed because the entire page must reload each time it’s posted back.

Ajax is well-suited to providing a user experience that doesn’t suffer from such problems. When a page uses Ajax to post back to the server, only the applicable form data is sent to the server in a process known as a partial postback. After the server processes that data, it responds with data that the page uses to dynamically update the page as necessary. During this process, the page remains visible in the browser. The result is a user experience very much like a Windows application instead of a typical browser-based experience.

The technology that Ajax uses is called XMLHttp. XMLHttp is a standardized method of exchanging data between an application and a web server. Almost all browsers support XMLHttp, and the latest Opera mobile browser allows for support of Ajax functionality from mobile devices and smart phones.

Microsoft’s ASP.NET Ajax

Microsoft’s implementation of Ajax is called ASP.NET Ajax. It includes the client-side Ajax (client-side libraries), server-side ASP.NET Ajax (the server-side controls that are available in the Expression Web toolbox), and the ASP.NET Ajax Control Toolkit (a collection of Ajax controls complete with source code).


Image Tip

Ajax is an acronym for Asynchronous JavaScript and XML.


Client-Side Ajax

The Microsoft client-side Ajax consists of client scripts and libraries that can be used to add Ajax functionality to any page. The client-side Ajax is the perfect choice, for example, for PHP developers who want to add Ajax functionality to a PHP application using Microsoft’s implementation. In fact, one of Microsoft’s employees has developed PHP for Microsoft client-side Ajax that does just that, and you can download it from codeplex.com/phpmsajax.


Image Tip

Microsoft is actually trending toward support of jQuery for Ajax functionality instead of using the Microsoft libraries exclusively. You can find more information on jQuery at jquery.com.


Server-Side Ajax

Server-side Ajax consists of a series of .NET Framework assemblies (DLL files) that include not only server-side functionality, but also ASP.NET controls that make using Ajax in an ASP.NET page a drag-and-drop endeavor. The following Ajax controls are included with Expression Web:

ScriptManagerThe ScriptManager control is required on any web form that uses Ajax. It provides the capability to dynamically include client-side scripts used in Ajax functionality.

ScriptManagerProxyThe ScriptManagerProxy control is used most often in content pages that use ASP.NET master pages. We’ll look at this control in more detail in the “Using Client-Side Ajax” section later in this chapter.

TimerThe Timer control enables you to easily perform postbacks of a page (both synchronous and asynchronous) at a regular interval.

UpdatePanelThe UpdatePanel control is a container for any control on a web form that takes part in an Ajax partial postback. We’ll use an UpdatePanel later in this chapter.


Image Note

We’ll use the client-side Ajax in the “Using Client-Side Ajax” section of this chapter, but I won’t go into great detail about it in this book. If you’re interested in reading more about it, read ASP.NET Ajax in Action from Manning. It’s an excellent book on Ajax.



Image Tip

Any web form that uses Ajax must have exactly one ScriptManager control, and it must appear above any control that uses Ajax; otherwise, an error will occur.


UpdateProgressThe UpdateProgress control is designed to display a message or some other indicator when an UpdatePanel is performing a partial postback.

Microsoft Ajax Control Toolkit

The Ajax Control Toolkit (which can be viewed and downloaded from http://www.asp.net/ajaxlibrary/act.ashx) is a set of Ajax controls that includes full source code. Microsoft released these controls to encourage developers to create their own Ajax controls using Microsoft’s server-side Ajax, and some of the coolest Ajax controls are included in the Toolkit.

Developing new Ajax controls and extenders is an advanced programming topic, and Microsoft has provided plenty of excellent documentation on the Ajax Control Toolkit site.


Image Note

Unfortunately, you cannot add controls from the Ajax Control Toolkit to the toolbox in Expression Web.


Adding Ajax Functionality to a Web Form

Adding Ajax functionality to your ASP.NET page is much easier than you might think. Let’s create a simple ASP.NET page, and then modify the page to add Ajax functionality to it.

Creating a Site and Page

Let’s create a new site and page, and then add Ajax functionality to the page using ASP.NET Ajax:

1. Create a new one-page site at a file location on the local computer so you can preview pages using the Microsoft Expression Development Server.

2. Select File, New, Page and select ASPX from the list of page types.

3. Select C# as the language and click OK to create the page.

4. Make sure you are in Design View.

5. Add about 15 lines of text. Any text will suffice, such as text generated by the Lorem Ipsum generator at www.lipsum.com.

6. From the ASP.NET section of the toolbox, add a DropDownList control under the text you added previously. Change the ID property of the DropDownList control to drpMusicGroup.

7. Change the AutoPostBack property of the DropDownList control to True.

8. Add a new line under the DropDownList control and add an ASP.NET Label control. Change the ID property of the Label control to lblDisplayGroup.

9. Add a new line and add a new Label control. Change the ID of the new Label control to lblTime.

10. Add 20 or so new lines so the text and controls scroll off the design surface.

Your page should now look like the one shown in Figure 31.1. Save the page as ajax.aspx.

Image

Figure 31.1. After you’ve finished creating the Web Form, it should look similar to the one shown here.

Next, you need to add some items to the DropDownList control. Click the arrow button at the top of the DropDownList control to display the DropDownList Tasks dialog; then click the Edit Items link as shown in Figure 31.2.

Image

Figure 31.2. The Edit Items link enables you to easily add and edit items in a DropDownList control.

Click Add and add a few of your favorite music groups, as shown in Figure 31.3; then click OK to add the items.

Image

Figure 31.3. Add a few of your favorite music groups to the DropDownList control.

Adding Server-Side Code

Now that you’ve created a simple page, you need to add some server-side code to process the page when a new item is selected in the DropDownList control. Switch to Code View and enter the code in Listing 31.1 directly above the opening <html> tag.

Listing 31.1. Server-Side Code for Ajax Page

<script runat="server">

    protected void Page_Load(object sender, System.EventArgs e)
    {
        lblTime.Text = "It is now " + System.DateTime.Now.ToString();
    }
    protected void drpMusicGroup_SelectedIndexChanged(object sender,
    System.EventArgs e)
    {
        string Group = drpMusicGroup.SelectedValue.ToString();
        lblDisplayGroup.Text = "You selected " + Group;
    }
</script>

This code is very simple. When the page loads, it displays the current date and time in the lblTime Label control. It also includes code that will run when a new value is selected in the drpMusicGroup DropDownList control. That code changes the lblDisplayGroup Label control so that it displays the group name you’ve selected.


Image Note

We haven’t begun adding Ajax capability to this page. The purpose of this exercise is to show you how easily you can build a page and then add Ajax functionality to it.


To make this page work, you need to change the code for the drpMusicGroup control to hook it up to the code you added to the page. To do that, be sure you’re in Code View and add the following to the opening <asp:DropDownList> tag on the page:

OnSelectedIndexChanged="drpMusicGroup_SelectedIndexChanged"

After you’ve added that, the opening <asp:DropDownList> tag should look like this:

<asp:DropDownList id="drpMusicGroup" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="drpMusicGroup_SelectedIndexChanged">

You’re now ready to test the page without Ajax functionality. Save the page and preview it in your browser. When the page loads, scroll down so the drop-down is at the top of the page; then select a new group. When you do, you’ll notice a couple of things happening. First, the page will scroll back to the top when you select a new group; then, the date and time change in the lblTime Label control. The reason for this is that the entire page is redrawn every time you select a different group.

Ajax is the perfect solution for a situation like this. By adding Ajax functionality to this page, you can update the lblDisplayGroup Label control when a new group is selected without changing anything else on the page.

Only two steps are involved in making this page Ajax-enabled:

1. Add a ScriptManager control to the page.

2. Add an UpdatePanel control to the page and place the controls you want Ajax-enabled into the UpdatePanel.

Adding a ScriptManager Control

As I mentioned earlier, any page that uses Microsoft’s server-side Ajax must have exactly one ScriptManager control on the page. The ScriptManager control also must be added to the page above any control that uses server-side Ajax; otherwise, an error will occur.


Image Tip

You can add your own scripts to the ScriptManager control as well. We’ll cover the concept of adding scripts to the ScriptManager in the “Using Client-Side Ajax” section of this chapter.


Ajax uses the ScriptManager control to load the necessary client scripts to support partial postbacks, the process of posting only certain data back to the web server.

Let’s add a ScriptManager control to the ajax.aspx page:

1. Open the ajax.aspx page if it’s not already open.

2. Add a new ScriptManager control on the page directly above the drpMusicGroup control. The ScriptManager control will likely show a warning icon as shown in Figure 31.4. If you don’t already have a web.config file that contains configuration information for the 3.5 .NET Framework, you need to add one before you can use ASP.NET Ajax.

Image

Figure 31.4. If you don’t already have a web.config file that contains .NET Framework 3.5 configuration information, Expression Web displays a warning icon on the new ScriptManager control.

3. To add the necessary configuration information, click the asp:scriptmanager link on the ScriptManager control shown previously in Figure 31.4. Expression Web displays a message informing you that you need to update or add a web.config file to support the .NET Framework 3.5, as shown in Figure 31.5. Click Yes to add the necessary information to your site.

Image

Figure 31.5. Expression Web can add the necessary information to your site to support the .NET Framework 3.5.

4. Save the page.

Your page should now look similar to the one shown in Figure 31.6.

Image

Figure 31.6. The ASP.NET page now has a ScriptManager control on it and can take advantage of server-side Ajax.

Adding an UpdatePanel Control

The UpdatePanel control is extremely powerful. Any control placed within an UpdatePanel control automatically becomes an Ajax enabled control. In the case of the ajax.aspx page, we want the drpMusicGroup and lblDisplayGroup controls to be Ajax enabled so that when an item is selected in the drop-down, the label is updated to reflect the selected item via Ajax. Accomplishing this is going to be a lot easier than you might think.


Image Tip

If you don’t see the UpdatePanel control after inserting it, select View, Visual Aids, Show to turn on Visual Aids.


You need to add a new UpdatePanel control that contains both controls. To do that, add the UpdatePanel; then cut and paste the controls into it:

1. Click to the right of the ScriptManager control, and press Enter to insert a new line above the drpMusicGroup control.

2. Add a new UpdatePanel control from the AJAX section of the ASP.NET Toolbox.

3. Select the drpMusicGroup and the lblDisplayGroup controls and select Edit, Cut to remove them and place them on the Windows Clipboard.

4. Click inside the new UpdatePanel control and select Edit, Paste to paste the controls inside the UpdatePanel control.

Believe it or not, you have just finished Ajax-enabling the page. If you preview the page in your browser and select an item in the drpMusicGroup drop-down, the lblDisplayGroup label will be populated with the appropriate group using ASP.NET Ajax. When that happens, you’ll notice that the page will no longer scroll to the top and the time that appears in the lblTime Label control reflects the time that the page was first loaded and not when you selected the group in the drop-down.

Using Client-Side Ajax

Client-side Ajax enables you to write client-side scripts that interact with your ASP.NET application. Suppose the code that runs when a new group is selected in the drpMusicGroup drop-down might take several seconds to run and return a value. In such a scenario, displaying a message to the user is a good practice, and client-side Ajax lets you easily do that.

In this section, we use client-side Ajax to display a status message while the Ajax request is executing.


Image Note

You can use the UpdateProgress control to display a message, but it’s a good idea to know how to take advantage of client-side Ajax in case you want a more customized solution.


Adding a <div> to the Web Form

You’ll need to add a <div> to the ajax.aspx page. The <div> will be used to display the status message.

Follow these steps to add the <div>:

1. Open the ajax.aspx page if it’s not already open.

2. Click to the right of the drpMusicGroup DropDownList control, and press Enter to add a new line.

3. Add a new <div> control to the new line from the Tags section in the HTML section of the Toolbox.

4. In the Tag Properties panel, change the id property of the <div> to WaitIndicator.

Creating the Client Library

The client library is a JavaScript file used to interact with the page during an Ajax partial postback. Follow these steps to create the client library:

1. Select File, New, Page to add a new file to the site.

2. Select JavaScript from the list of file types and click OK.

3. Select File, Save and save the JavaScript file as ClientLibrary.js.

Now you must add the JavaScript that will update the <div> you added earlier with a status message. Add the following JavaScript code to the ClientLibrary.js file:

Sys.Net.WebRequestManager.add_invokingRequest(App_InvokeRequest);
Sys.Net.WebRequestManager.add_completedRequest(App_CompleteRequest);

function App_InvokeRequest(sender, eventArgs)
{

    var waitDiv = $get("WaitIndicator");
    waitDiv.innerHTML = "Please wait...";


}

function App_CompleteRequest(sender, eventArgs)
{
    var waitDiv = $get("WaitIndicator");
    waitDiv.innerHTML = "";


}


Image Note

A detailed discussion of client-side Ajax is outside the scope of this book. For detailed information on using client-side Ajax, see http://msdn.microsoft.com/en-us/library/bb397536.aspx.


The first few lines of code add the event handlers that fire when the Ajax request begins (the invokingRequest event) and ends (the completedRequest event). These lines use the Sys.Net.WebRequestManager object, which is provided by client-side Ajax.

The App_InvokeRequest and App_CompletedRequest functions set the innerHTML property of the <div> you added earlier using the $get method the client-side Ajax provides. The $get method returns a reference to the control whose ID is passed to it.

After you’ve added the code to the ClientLibrary.js file, save the file.

Adding the Client Script to the ScriptManager Control

The final step is to add the ClientLibrary.js file to the ScriptManager’s Scripts collection. As I mentioned earlier in this chapter, you can add your own client scripts to the ScriptManager control. When you do, AjaxASP.NET Ajax loads your scripts dynamically.

Follow these steps to add the ClientLibrary.js script to the ScriptManager’s Scripts collection:

1. Select the ScriptManager control you added to the ajax.aspx page earlier.

2. Click the ellipse button for the Scripts property in the Tag Properties panel as shown in Figure 31.7.

Image

Figure 31.7. You can use the Scripts property in the Tag Properties panel to add your own scripts to the ScriptManager control.

3. Click the Add button in the ScriptReference Collection Editor.

4. Change the Path property of the new ScriptReference to ClientLibrary.js (see Figure 31.8).

Image

Figure 31.8. The Path property points to the script you want to add.

5. Click OK and save the page.

When the ajax.aspx page is browsed, the ScriptManager loads the ClientLibrary.js script.

If you browse to the page right now, the script we added displays a message that says Please wait... while the Ajax request is being processed. However, because the Ajax request is almost instantaneous in our test page, we need to build in a delay so we can see the effect.

Open the ajax.aspx page and add the following code to the Page_Load event you added earlier:

if (IsPostBack) System.Threading.Thread.Sleep(7000);

After you add that code, the Page_Load event looks like the following code:

protected void Page_Load(object sender, System.EventArgs e)
{
    if (IsPostBack) System.Threading.Thread.Sleep(7000);
    lblTime.Text = "It is now " + System.DateTime.Now.ToString();
}

This code makes the page wait seven seconds when the Ajax partial postback takes place, enabling you to see the Please wait... message. You can now save the page and preview it to see the status indicator displayed.

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

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