How to work with client callbacks in an ASP.NET Web application


In this topic


The source code for this walkthrough is included in the SampleCallback.aspx page in the sample Common_Callback.

About working with client callbacks in an ASP.NET Web application

Developing an ASP.NET 2.0 Web application that uses client callbacks involves the following two general steps:
  1. Create the server-side code to be invoked by the client.
  2. Create the client-side code to invoke the callback request and process the response.
The message in the callback request and response is always a string. You determine the content and format of the string. The request usually includes a string that directs the server to perform a specific action as well as user-provided data. The response usually contains content to be rendered on the client or data to trigger further actions.
This topic assumes that you have created a standard, empty ASP.NET Web application. 

Implementing client callbacks

Perform the following steps to implement client callbacks in an ASP.NET Web page:
  1. Implement the System.Web.UI.ICallbackEventHandler. The ICallbackEventHandler interface can be implemented on a page or a Web control. The interface contains two key methods: RaiseCallbackEvent(string EventArgs) and GetCallbackResult(). RaiseCallbackEvent() receives the message in the callback request sent from the client. It parses the message and determines what server-side logic will be executed. Once the server-side code is finished, it creates a string of values to be sent to the client using the GetCallbackResult() method.

    The following code is an implementation example of both methods—behind the Default.aspx.cs page. The eventArgument is updated via a callback request from the client.
[C#]
public partial class Default: System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    string returnstring;
    string ICallbackEventHandler.GetCallbackResult()
    {
        return returnstring;
    }
    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        if (eventArgument == "getservertime")
        {
            returnstring = DateTime.Now.ToString();
        }
    }
  1. Call the GetCallbackEventReference method on the Page class. The GetCallbackEventReference method creates a JavaScript string on the client Web page to start the callback. The usage and method parameters are as follows:
Usage: GetCallbackEventReference
Parameter name
Description
control
The control or page that implements ICallbackEventHandler.
argument
The name of a client-side JavaScript variable. References the string sent to the RaiseCallbackEvent method via the eventArgument parameter.
clientCallback
The name of the client-side JavaScript function that receives the result of a successful server event.
context
The name of a client-side JavaScript variable. Usually used to determine the content of the message (argument) in the callback request. The value of the variable is stored on the client as the context parameter associated with a callback.
clientErrorCallback
The name of the client-side JavaScript function that receives the callback result when an error occurs.
useAsync
A Boolean that determine whether a synchronous or asynchronous callback is made to the server.
The following code shows an example of the GetCallbackEventReference method. The sCallBackFunctionInvocation member variable is a public string, global to the Page class:
[C#]
public string sCallBackFunctionInvocation;
protected void Page_Load(object sender, EventArgs e)
{
    sCallBackFunctionInvocation = Page.ClientScript.GetCallbackEventReference(this, 
        "message", "processMyResult", "context", "postMyError", true);
}
At runtime, when the Web page is first loaded, the GetCallbackEventReference method generates a JavaScript string that contains the WebForm_DoCallback function with the previously listed parameters.
  1. Create the client-side code to trigger the callback and process the response. Implementing System.Web.UI.ICallbackEventHandler and calling GetCallbackEventReference adds a line similar to the following script tag in your aspx page at runtime:
[JavaScript]
 < script src = 
     "/MyWebsite/WebResource.axd?d=TqQApA1CcEIyShhLjzTczw2&t=632657807109074470"
     type = "text/javascript" >  <  / script >
WebResource.axd, a Hypertext Transfer Protocol (HTTP) handler included with ASP.NET 2.0, enables Web page and Web control developers to download resources that are embedded in an assembly. The System.Web.dll contains a JavaScript resource that contains the WebForm_DoCallback function. The format of this uniform resource locator (URL) is WebResource.axd?d=encrypted identifier&t=time stamp value. The "d" refers to the requested Web resource and is an encrypted string of the assembly name and resource name. The "t" is the time stamp for the requested assembly, which can help determine if there have been any changes to the resource. At runtime, the JavaScript resource is downloaded to the client.
The ASP.NET 2.0 callback framework includes JavaScript content to support callbacks. WebForm_DoCallback is the JavaScript function that initiates and manages callbacks in the client browser. It creates an ActiveX object (Microsoft.XMLHTTP) for Internet Explorer (pre-7.0) browsers or a native XMLHttpRequest object for other browsers to manage HTTP communication with a Web application on the server. The Microsoft.XMLHTTP object is packaged with the Microsoft Extensible Markup Language (XML) (MSXML) Document Object Model (DOM), part of the MSXML set of components.
The following code provides an example of the Hypertext Markup Language (HTML) content in an aspx page configured to work with callbacks:
[JavaScript]
 < html >  < head >  < title > Untitled Page <  / title >  < script language = 
     "javascript" type = "text/javascript" > function getServerTime(){
    var message = 'getservertime';
    var context = 'Page1';
     <  %= sCallBackFunctionInvocation %  > 
}

function processMyResult(returnmessage, context){
    var timediv = document.getElementById('timelabel');
    timediv.innerHTML = returnmessage;
}

function postMyError(returnmessage, context){
    alert("Callback Error: " + returnmessage + ", " + context);
}

 <  / script >  <  / head >  < body >  < form id = "form1" runat = "server" >  <
     input type = "button" value = "Get Server Time" onclick = "getServerTime();" / 
     >  < div id = "timelabel" >  <  / div >  <  / form >  <  / body >  <  / html >
The edits to the code involve the following steps:
    1. Add an HTML element and a JavaScript function to create a callback request. In the previous HTML code, the click event of an HTML button triggers a call to the getServerTime JavaScript function, which in turn calls WebForm_DoCallback. The message variable is set to getservertime, which is used by the server to determine the action to execute. The <%=sCallBackFunctionInvocation%> server variable is translated to WebForm_DoCallback('__Page', message, processMyResult, context, postMyError, true) at runtime.
    2. Add two JavaScript functions to process the callback response and update the page. The processMyResult function takes the callback response string and updates the text content of a div tag in the HTML page. This occurs dynamically so other objects in the page are not redrawn. The postMyError function receives the callback message if an error occurs on the server. If an error occurs, an alert box appears.

Callback events

The following diagram illustrates a callback event at runtime. The green circles indicate the order in which events occur to initiate and process the callback. A description of each step is provided.
  1. After the Web page loads, the onClick event of an HTML button is triggered, which calls the user-defined getServerTime JavaScript function.
  2. The getServerTime function sets the message and context variables to be sent to the server and calls the ASP.NET 2.0 defined WebForm_DoCallback function to create and send the callback request.
  3. A new XMLHttpRequest object is created to send and receive the asynchronous call to and from the server.
  4. The XMLHttpRequest object posts the HTTP request to the server containing the message. On the server, the RaiseCallbackEvent method parses the argument (message) and executes business logic—in this case, it converts the time on the server to a string. The GetCallbackResult method passes this string back to the XMLHttpRequest object waiting on the client.
  5. The ASP.NET 2.0 WebResource for callbacks directs the callback response string to the registered callback response function, the user-defined processMyResult function.
  6. The processMyResult function uses the content of the callback response string to dynamically update HTML in the Web page. In this case, it inserts HTML into an existing <div> tag to display the server time.


See Also:

Working with AJAX and ASP.NET
How to work with partial postbacks in an ASP.NET Web application