Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

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 <img> 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 <img> control is then automatically added to the Panel control to display the Amazon.com logo.

Switch Default.aspx to Source View and wrap the <asp:Image> element with the <a> element:

<a href="" id="BookURL">
   <asp:Image ID="Image1" runat="server" 
      ImageUrl="~/Images/harrypotter.jpg" />
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 <script> element into the <head> element of the page:

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

function ShowCover(){
   var Command = "1:" +    
   var context = new Object();
   context.CommandName = "ShowCover";

   window.status="Retrieving cover...";

function CallBackHandler(result, context) {
   // Show the cover from Amazon.com
   if (context.CommandName == "ShowCover") {
      var indexofComma = result.indexOf(",");

      // display using the Image URL
      var ImageURL = result.substring(0,indexofComma);
      // Update the URL of the book
      var BookURL =
      document.links("BookURL").href =  BookURL;
      window.status="Retrieving cover...Done.";
// handler for error
function onError(message, context) {
  alert("Exception :\n" + message);
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):

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

function ShowCover(){
   var Command = "1:" +
   var context = new Object();
   context.CommandName = "ShowCover";

   window.status="Retrieving cover...";
      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):

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:

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:

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 _

        ' Show Cover
        If eventArgument.StartsWith("1:") Then

            '---strips away the command
            eventArgument = eventArgument.Substring(2)

            ' Using Amazon's search
            Dim Search As New _
            Dim ISBNReq As New _
            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
            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).

Thanks for your registration, follow us on our social networks to keep up-to-date