Browse DevX
Sign up for e-mail newsletters from DevX


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

With applications like Google Maps for inspiration, it seems everybody's been talking about what you can do with AJAX. But many don't know that writing AJAX-style applications that can do partial screen refreshes without a trip to the server are easy to write in ASP.NET using the built-in Client Callback Manager.

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:

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:

<head runat="server">
  <title>Untitled Page</title>

function GetStockPrice(){
   var Command = "2:"
   var context  = new Object();
   context.CommandName = "GetStockPrice";

   window.status="Retrieving stock prices...";
   setTimeout("GetStockPrice()", 10000); 

function CallBackHandler(result, context) {
   // Show the cover from Amazon.com
   if (context.CommandName == "ShowCover") {
   // Display Stock Prices
   if (context.CommandName == "GetStockPrice") {
      var count = 0;
      while (result.length>0) {
         var indexofComma = result.indexOf(",");
         // extract individual values
         var Value = result.substring(0,indexofComma);
         result = result.substring(indexofComma+1)
            case 0: {document.forms[0].
                    elements['txtMSFTPrice'].value = 
                    Value; break}
            case 1: {document.forms[0].
                    elements['txtMSFTChange'].value = 
                    Value; break}    
            case 2: {document.forms[0].
                    elements['txtAAPLPrice'].value = 
                    Value; break}
            case 3: {document.forms[0].
                    elements['txtAAPLChange'].value = 
                    Value; break}
      window.status="Retrieving stock prices...Done.";
This time round, the string to send to the server would simply be:

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...";
   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. _

        ' 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 _
            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
            Throw (New Exception( _
               "Command not recognized"))    
        End If
    End Function
End 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:

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.

Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Thanks for your registration, follow us on our social networks to keep up-to-date