devxlogo

Write AJAX-style Applications Using the ASP.NET 2.0 Client Callback Manager

Write AJAX-style Applications Using the ASP.NET 2.0 Client Callback Manager

t seems everybody is talking about AJAX these days. The technology behind AJAX is hardly new, yet some really ‘killer’ new applications of XMLHttpRequest object have emerged recently, and these have breathed new life and excitement into the concept of client-side image refresh.

The most notable of these new applications is Google’s Google Maps. Using the Google Maps (see Figure 1), you can search for a location in the U.S. and then zoom in into the map and drag and roll the map without needing to refresh the page.

AJAX is a collection of technologies that has been around since the early days of the Web. Here is what AJAX incorporates (according to Jesse James Garrett, who first coined the term ‘AJAX’ for Asynchronous JavaScript + XML):

  • standards-based presentation using XHTML and CSS;
  • dynamic display and interaction using the Document Object Model;
  • data interchange and manipulation using XML and XSLT;
  • asynchronous data retrieval using XMLHttpRequest;
  • and JavaScript binding everything together.
Figure 1. Google Maps: Go ahead and zoom right down to the street level. You’ll never have to do a server refresh.

In a nutshell, AJAX allows you to write responsive Web applications that do not need to constantly refresh the page in order to update the information on the page.

Unknown to some, ASP.NET 2.0 includes the Client Callback Manager to allow developers to write AJAX-style Web applications. The Client Callback Manager uses XMLHTTP behind the scenes to encapsulate the complexities in sending data to and from the servers and clients (hence for it to work, you need a Web browser that supports XMLHTTP; at the moment the Client Callback Manager only works with Microsoft Internet Explorer.

In this article, I will show you how to use the Client Callback Manager to write AJAX-style applications.

Displaying Book Covers
To illustrate how the ASP.NET 2.0 Client Callback Manager works, I’ll build a Web application that allows users to view the covers of books by downloading them from the Amazon Web service. The user simply needs to enter the ISBN number of a book and then the page will download the cover image from Amazon.com, without needing to refresh the page.

To start, launch Visual Studio 2005 beta 2 and create a new Web Site project. Name the project C:ClientCallBack. Populate the default Web Form (Default.aspx) with the controls as shown in Figure 2, including panel, textbox, button, and image controls.

Figure 2. Form Wizard: Populate the form with the controls shown.

For the control, you can simply use Internet Explorer to load Amazon.com’s home page and then drag and drop the logo image (see Figure 3) onto the Panel control. An control is then automatically added to the Panel control to display the Amazon.com logo.

Switch Default.aspx to Source View and wrap the element with the element:

   

Essentially, this will make the book cover image a hyperlink and the user can click on the book image to go to Amazon.com to view more information about the book.

Also, in the Properties window for the Show Cover button (btnShowCover), set the OnClientClick property to “ShowCover.” This means that when the user clicks on this button, a client script (Javascript in this case, which I will code shortly) function named ShowCover() will execute.

Writing the JavaScript

Figure 3. Branding the App: Add the logo from Amazon.com to your panel control.

I’ll now write the client-side code (JavaScript), which will perform the job of sending the request back to the server. In the Source View of Default.aspx, insert the portion of the code below embedded within the

Note that you have defined three functions in this case: ShowCover(), CallBackHandler, and onError(). The ShowCover() function formulates the request to be sent to the server side; in this case, it takes the value of the TextBox control (txtISBN) and puts it into the callbackStr variable (I will define this variable in the code behind of the form later on). A command string to be posted to the server looks like this ("1:" followed by the ISBN number of a book):

1:0375824839

The <%=callbackStr%> statement will insert the generated string into the function, so that during runtime it becomes:

function ShowCover(){   var Command = "1:" +      document.forms[0].elements['txtISBN'].value;   var context = new Object();   context.CommandName = "ShowCover";   window.status="Retrieving cover...";   WebForm_DoCallback('__Page',Command,      CallBackHandler,context,onError, false)}

Notice that the function returns the call to the CallBackHandler() function. The CallBackHandler() function will be invoked when the server returns the result to the client. If you are sending multiple requests to the server, there is a need to differentiate who the return caller is. So you use the context variable to set the command name for each type of call ("ShowCover").

The result will be returned via the result variable in the CallBackHandler() function. The result may look like this (there are two URLs in this string separate by a comma: the first points to the cover image of the book and the second points to the URL of the book in Amazon.com):

http://images.amazon.com/images/P/0374292884.01.MZZZZZZZ.jpg,http://www.amazon.com/exec/obidos/ASIN
/0374292884/xxxx?dev-t=04Q4HFNSENYJ711BK2G2%26camp=2025%26link_code=sp1

The result is then parsed and displayed accordingly in the controls on the page.

The onError() function displays an alert window on the client displaying the error message when the server throws an exception.

Now that the client-side coding is done, so I'll move on to the code-behind of the Web Form (Default.aspx.vb).

Adding the Code-Behind
First, you need to add a Web Reference to the Amazon.com Web service. To do so, right-click on the project name in Solution Explorer and then select 'Add Web Reference…' Enter the following URL, which is the location of the WSDL for the Amazon Web service, and click Go:

http://soap.amazon.com/schemas3/AmazonWebServices.wsdl 

Use the default name of com.amazon.soap and click Add Reference.

The Web form that is going to receive the callback needs to implement the ICallbackEventHandler interface. You will also declare the callbackStr variable here:

Partial Class _Default    Inherits System.Web.UI.Page    Implements ICallbackEventHandler    Public callbackStr As String

In the Page_Load event, you need to generate the code that performs the call back using the GetCallbackEventReference() method of the Page class. You also modify the Show Cover button so that clicking on it will not cause a postback to the server (instead, the client-side function ShowCover() will be executed):

    Protected Sub Page_Load(ByVal sender As Object, _       ByVal e As System.EventArgs) Handles Me.Load        btnShowCover.Attributes.Add("onClick", _           "return false")        callbackStr = _           Page.ClientScript. _           GetCallbackEventReference(Me, _           "Command", "CallBackHandler", _           "context", "onError", False)    End Sub
Figure 4. Testing the Application. The finished application shows the book cover image without "flicker," i.e. calling to the server.

In essense, the callbackStr variable will store the following string:

WebForm_DoCallback('__Page',Command,CallBackHandler, context,onError, false)

What is important here is that Command is referring to the string that is going to be passed to the server, while CallBackHandler refers to the function that is invoked (on the client) when the server returns a result to the client.

The ICallbackEventHandler interface has one method to implement: the RaiseCallbackEvent() function. This function is invoked when the client sends a request to the server. In this case, you need to connect to Amazon.com's Web service and fetch the detailed information of a book based on its ISBN number. The URL of the book cover as well as the URL of the book will be returned as a string separated by a comma:

    Public Function RaiseCallbackEvent( _       ByVal eventArgument As String) As String _       Implements _       System.Web.UI.ICallbackEventHandler._       RaiseCallbackEvent        ' Show Cover        If eventArgument.StartsWith("1:") Then            '---strips away the command            eventArgument = eventArgument.Substring(2)            ' Using Amazon's search            Dim Search As New _                com.amazon.soap.AmazonSearchService()            Dim ISBNReq As New _               com.amazon.soap.AsinRequest            With ISBNReq                .asin = Trim(eventArgument)                .devtag = "your_dev_tag"                .type = "heavy"                .tag = "xxxx"            End With            ' Perform a search request            Dim BookInfo As com.amazon.soap.ProductInfo            BookInfo = Search.AsinSearchRequest(ISBNReq)            'return the cover URL            Return BookInfo.Details(0).ImageUrlMedium & _                   "," & BookInfo.Details(0).Url        Else            Throw (New Exception( _               "Command not recognized"))            End If    End Function

That's it! Press F5 to test the application. Enter an ISBN number in the textbox and then click the Show Cover button. You will see that the cover of the book is displayed on the page without needing to refresh (you can observe that the page does not flicker). Also, you can click on the image to bring you to the page containing more detailed information of the book (see Figure 4).

A Continually Updating Application of AJAX
While it is cool that you can update a page without refreshing it, a much better use of the Client Callback manager would be for applications that require constant updating. For example, you might want to monitor stock prices on a Web page. Using conventional Web pages you need to constantly refresh the page in order to obtain the latest stock prices.

In this section, I will build a stock ticker on a Web page and use the Client Callback manager to constantly update the stock prices without refreshing the page.

To get the latest stock prices, I'll use a stock Web service available at:

http://www.swanandmokashi.com/HomePage/WebServices/StockQuotes.asmx?wsdl

Add a Web Reference to the above URL and use the default name of com.swanandmokashi.www.

In the same Default.aspx page, add the controls shown in Figure 5, including the 3x2 table and the button control.

Figure 5. Stock Ticker Form: Populate the form with the controls shown for the stock ticker application. Because I'm continuing from the earlier application, some controls persist.

Set the OnClientClick property of the Start Stocker Ticker button to "GetStockPrice()." Switch to the Source View of the Web Form and then add the code in bold from below:

...  Untitled Page 

This time round, the string to send to the server would simply be:

2:

To cause the stock prices to self-update at regular time interval, you will use the setTimeout() function in JavaScript to call the GetStockPrice() function at regular time intervals (set to be 60,000 in this case, which is 60 seconds):

function GetStockPrice(){   var Command = "2:"   var context  = new Object();   context.CommandName = "GetStockPrice";   window.status="Retrieving stock prices...";   <%=callbackStr%>   setTimeout("GetStockPrice()", 60000); }

On the server side, add the following in bold to the code-behind of Default.aspx. You will access the stock Web service and then return the stock information as a string:

Partial Class _Default    Inherits System.Web.UI.Page    Implements ICallbackEventHandler    Public callbackStr As String    Protected Sub Page_Load(ByVal sender As Object, _       ByVal e As System.EventArgs) Handles Me.Load        btnShowCover.Attributes.Add("onClick", _           "return false")        btnStart.Attributes.Add("onClick", _           "return false")        callbackStr = Page.ClientScript. _           GetCallbackEventReference(Me, _           "Command", "CallBackHandler", _           "context", "onError", False)    End Sub    Public Function RaiseCallbackEvent( _       ByVal eventArgument As String) As String _       Implements _       System.Web.UI.ICallbackEventHandler. _       RaiseCallbackEvent        ' Show Cover        If eventArgument.StartsWith("1:") Then           ...        ElseIf eventArgument.StartsWith("2:") Then            '---stock web service            Dim resultString As String = String.Empty            '---access the stock web service            Dim ws As New _               com.swanandmokashi.www.StockQuotes            Dim result() As com.swanandmokashi.www.Quote            '---get the stock quote for MSFT            result = ws.GetStockQuotes("MSFT")            resultString = result(0).StockQuote & "," & _               result(0).Change & ","            '---get the stock quote for AAPL            result = ws.GetStockQuotes("AAPL")            resultString += result(0).StockQuote &  _               "," & result(0).Change & ","            ' return the result            Return resultString        Else            Throw (New Exception( _               "Command not recognized"))            End If    End FunctionEnd Class
Figure 6. Trying the Stock Ticker Application: The stock ticker appears below the earlier book cover image application, but its fast, "flickerless" performance is the same.

A typical return string would look like:

25.70,+0.24,35.84,+0.48

That's it! Press F5 to test the application. Click on the Start Stock Ticker button and observe that the stock values changes every minute (see Figure 6). Be sure to try this during the hours in which the stock market is open (generally, 9:30 a.m. to 4:00 p.m. EST?adjust for your time zone accordingly).

In this article, I've shown you how easy it is to write AJAX-style applications in ASP.NET. Once you overcome the initial hurdle of getting everything set up (especially the need to write some JavaScript on the client side), you will find that it is really easy to adapt one example and use it for another scenario. In fact, there are so many good uses of the Client Callback Manager that the only limiting factor is your creativity.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist