Total Recall

Implementing ASP.NET 2.0 Script Callback

LANGUAGES: ALL

ASP.NET VERSIONS: 2.0

One of the main issues developers faced when they first started to develop commercial Web sites was the inherent limitation of using a browser-based interface. For instance, there were many cases where you wanted to retrieve information from the server after the user had performed some action, like entering an employee number in a Web page to retrieve the details of an employee. To accomplish this, you would post the current page to the server, retrieve the employee information from the database, and refresh the page to display the new content.

Although this method of refreshing the whole page is very common today, it is inefficient because the Web page refreshes and re-renders the entire page of content even if only a small percentage of the page has actually changed. Refreshing of the page not only results in delays and is a waste of resources, but it also greatly impacts the user experience. However, if the same functionality can be produced without refreshing the page, it can significantly enhance the user experience. To accomplish this, you need a way to execute a piece of code on the server without refreshing the page, which is exactly what ASP.NET 2.0 script callback allows you to do. This article will provide you with an in-depth understanding of this feature by discussing code examples.

 

The Need for Script Callback

How many times have you been on a Web page and selected a value in a dropdown box, only to suddenly see the whole page refresh its display so that it can fetch values for another dropdown box or populate some other control? You can see this demonstrated in many Web sites. As previously mentioned, this refreshing behavior not only results in delays, it also frustrates the users. In the ASP world, this problem was solved by the use of remote scripting technology. Using remote scripting, you could make a hidden request to the server and execute a method, which returns only the data that needs to be changed on the page. The result is a smoother user experience.

 

With .NET gaining momentum, though, most companies are looking to migrate their existing ASP applications to ASP.NET to take advantage of the new features provided by the .NET Framework. Even though remote scripting is a powerful feature, ASP.NET 2.0 provides an efficient alternative to invoke a remote function from a server page without refreshing the browser. This new feature is called ASP.NET 2.0 script callback, and it builds on the foundation of the XmlHTTP object library. Using the ASP.NET 2.0 script callback feature, you can emulate some of the behaviors of a traditional fat-client application in a Web-based application. It can be used to refresh individual controls, validate controls, or even to process a form without having to post the whole page to the server.

 

The Callback Feature in an ASP.NET Page

In this article, we ll consider an example wherein we retrieve the details of an employee based on the employee number entered in the Web page. We ll leverage the script callback feature in this scenario and demonstrate how we can retrieve the employee details without posting the page back to the server.

 

Before we look at the example, let s understand the steps involved in using the callback feature:

  • The client invokes a client-side method that will use the callback manager.
  • The callback manager creates the request to an .aspx page on the server.
  • The server receives the request and processes the request by invoking a pre-defined sever-side function named RaiseCallbackEvent. Then it returns the results to the callback manager in the client side.
  • The callback manager receives the server response and calls a callback method located on the client-side. If there is an error during the server-side processing, the callback manager invokes a separate callback method.
  • The client callback method processes the results of the server-side call.

 

Let s first create a new ASP.NET Web site by selecting New Web Site from the File menu in Visual Studio 2005. Click on the Browse button in the New Web Site dialog box. In the Choose Location dialog box, select Local IIS in the left navigation pane and create a virtual directory named ScriptCallback under MyProjects\aspnetPro, then click Open. Now in the New Web Site dialog box, the location should read http://localhost/MyProjects/aspnetPro/ScriptCallback.

 

After the Web site is created, add a new Web Form by right-clicking on the Web site and selecting Add New Item from the context menu. In the Add New Item dialog box, select Web Form from the list of templates. Change the name of the file to CallbackExample.aspx and click Add. Modify the code in the CallbackExample.aspx file to read as shown in Listing One.

 

Let s spilt the implementation shown in Listing One into three steps:

  • Implementing the server-side event for callback.
  • Generating the client-side script for callback.
  • Implementing the client callback method.

 

Let s go through each of these steps in detail.

 

Implementing the Server-side Event for Callback

At the top of the page, we import the required namespaces by using the Import directive. After that, we use the Implements directive to implement the ICallbackEventHandler interface. This interface has a method named RaiseCallbackEvent that must be implemented to make the callback work:

 

<%@ Implements Interface=

 "System.Web.UI.ICallbackEventHandler" %>

 

The signature of the RaiseCallbackEvent method is shown here:

 

public string RaiseCallbackEvent(string eventArgs)

 

It takes an argument of type string. You should use this string argument if you need to pass values to the server-side method. Inside the RaiseCallbackEvent method, we first convert the supplied employee ID into an integer type and then invoke a function named GetEmployeeDetails, passing in the employee ID as an argument:

 

int value = Int32.Parse(eventArgs);

return GetEmployeeDetails(value);

 

As the name suggests, the GetEmployeeDetails method simply retrieves the details of the employee and returns that information in the form of an XML string. This method starts by retrieving the connection string from the web.config file by using the following line:

 

string connString = System.Configuration.ConfigurationSettings.

       ConnectionStrings["northwindConnectionString"].

       ConnectionString;

 

The above line of code retrieves the connection string from the ConnectionStrings section of the web.config file. The connection string is stored in the web.config as follows:

 

 

    connectionString="server=localhost;uid=sa;pwd=thiru;

    database=Northwind"/>

 

After the connection string is retrieved, we then create an instance of the SqlConnection object passing in the connection string as an argument. Then it creates instances of DataSet, SqlDataAdapter, and SqlCommand objects, passing in the appropriate parameters to their constructors. Then it executes the SQL query by invoking the Fill method of the SqlDataAdapter object. After the query is executed and the results are available in the DataSet object, we then invoke the GetXml method of the DataSet object to return the XML representation of the DataSet to the caller. The RaiseCallbackEvent method receives the returned XML string and simply returns it to the caller.

 

Generating the Client-side Script for Callback

Let s move our focus to the Page_Load event of the page. In the beginning of the Page_Load event, we check to see if the browser supports callback by examining the SupportsCallback property of the HttpBrowserCapabilities object:

 

if (!Request.Browser.SupportsCallback)

 throw new ApplicationException

  ("This browser doesn't support " +

         "Client callbacks.");

 

Then we invoke the Page.GetCallbackEventReference method to implement the callback in client side. You can use this method to generate client-side code, which is required to instantiate the asynchronous call to server:

 

string src = Page.GetCallbackEventReference(this, "arg",

 "DisplayResultsCallback", "ctx", "DisplayErrorCallback");

 

Let s understand the arguments passed to the GetCallbackEventReference method:

  • this. Control that implements ICallbackEventHandler(Current Page)
  • arg. String to be passed to server side as argument.
  • DisplayResultsCallback. Name of the client-side function, which will receive the result from the server-side event.
  • ctx. String to be passed from one client-side function to another client-side function through context parameter.
  • DisplayErrorCallback. Name of the client-side function that will be called if there is any error during this process.

 

When you execute this page from the browser and view the HTML source code, you ll see that the following callback code is generated because of the previously mentioned GetCallbackEventReference method call:

 

WebForm_DoCallback('__Page',arg,DisplayResultsCallback,

                  ctx,DisplayErrorCallback)

 

WebForm_DoCallback is a JavaScript function (introduced in ASP.NET 2.0) that in turn invokes the XmlHttp class methods to actually perform the callback.

 

We then embed the callback code inside a function by concatenating the callback-generated code with a JavaScript function named GetEmployeeDetailsUsingPostback using the following code:

 

string mainSrc = @"function " +

 "GetEmployeeDetailsUsingPostback(arg, ctx)" +

 "{ " + src + "; }";

 

Finally, we register the client script block through the RegisterClientScriptBlock method call. Note that in ASP.NET 2.0, the Page.RegisterClientScriptBlock and Page.RegisterStartupScript methods are obsolete. That s why we had to take the help of Page.ClientScript to render client-side script to the browser. The Page.ClientScript property returns an object of type ClientScriptManager, which is used for managing client scripts.

 

Implementing the Client Callback Method

In the client side, we have a method named GetEmployeeDetails, which is invoked when the Get Employee Details command button is clicked:

 

function GetEmployeeDetails()

   {

   var n = document.forms[0].txtEmployeeID.value;

   GetEmployeeDetailsUsingPostback(n, "txtNumber");

 }

 

From within the GetEmployeeDetails method, we invoke a method named GetEmployeeDetailsUsingPostback and pass in the required parameters. Note that the definition of the GetEmployeeDetailsUsingPostback method is added in the Page_Load event in the server side (through the RegisterClientScriptBlock method call).

 

After the server-side function is executed, the callback manager automatically calls the DisplayResultsCallback method. Let s look at the code of the DisplayResultsCallback method. In our example, because the value returned from the server-side page is an XML string, we load the returned XML into an XMLDOM parser and then display its contents:

 

objXMLDoc = new ActiveXObject("Microsoft.XMLDOM");

//Load the returned XML string into XMLDOM Object

objXMLDoc.loadXML(strXML);   

 

Then we get a reference to the Employees node by invoking the selectSingleNode method of the MSXML DOM object:

 

objEmployee = objXMLDoc.selectSingleNode

              ("EmployeesRoot").selectSingleNode

              ("Employees");

 

If a valid Employees element is returned from the function call, we display its contents. We display this information in a div tag by setting the innerHTML property of the div element to the dynamically constructed HTML.

 

When you browse to the CallbackExample.aspx file using the browser and search for an employee with an employee ID of 1, the output should be somewhat similar to that shown in Figure 1. When you click the Get Employee Details button, you ll notice that the employee information is retrieved from the server and displayed in the browser; all without refreshing the page.

 


Figure 1: Retrieve employee information from the server and display it in the browser without refreshing the page.

 

Conclusion

The callback capability in ASP.NET 2.0 is an extremely useful feature that can go a long way in increasing the usability of a Web application by obviating the need to perform postbacks. You can implement callbacks to retrieve lookup data, perform validation, execute back-end code, and so on. Callbacks can also play an important role in increasing the performance of a Web application by fetching only relevant data asynchronously.

 

This article provides a thorough discussion of the script callback feature in ASP.NET 2.0. This article also provides an example of how to use this new feature to create dynamic, interactive Web applications that provide a rich user experience. Although the application we created was simple in functionality, it should provide a solid foundation for understanding how to migrate existing ASP-based remote scripting applications to ASP.NET 2.0 using the script callback feature.

 

The sample code in this article is available for download.

 

Thiru Thangarathinam works at Intel Corp. in Chandler, AZ. He specializes in architecting, designing, and developing distributed enterprise class applications using .NET-related technologies. He has co-authored a number of books in .NET-related technologies. He has also been a frequent contributor to leading technology-related online publications. He can be reached at mailto:[email protected].

 

Begin Listing One

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data"%>

<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Xml"%>

<%@ Implements

 Interface="System.Web.UI.ICallbackEventHandler" %>

 ASP.NET 2.0 Script Callback Example

 

 

>

  

Employee Details

  

  

  Enter the Employee ID:

       

  

    style="LEFT: 149px; TOP: 72px">

  

    value="Get Employee Details" name="btnGetEmployee"

    onclick="GetEmployeeDetails()">

  

  

  

  

 

End Listing One

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish