Developing applications using the Web ADF - ASP.NET Integration  

AJAX and ASP.NET

 


Interaction with a Web application can be initiated via a synchronous or asynchronous request from the client to the server.  The traditional ASP.NET Web page model uses a synchronous request to initially load a page and its content.  Subsequent interaction with the page uses synchronous full page postbacks, which are usually triggered on the client by submitting an html form.  A postback merely involves posting data back to the existing page on the server in the same session.  During a full-page postback, the Web page and controls are recreated and a new version of the entire Web page is rendered on the client.  In addition, most of the application logic is present on the server-side.   Unfortunately full page postbacks often introduce a great deal of processing overhead which can decrease performance.  Since the entire page must be reconstructed via a synchronous request to the server, the client must wait for a response to continue working.  On the other hand, asynchronous requests can improve performance and enhance the end user experience when working with a Web application.   Asynchronous requests utilize a set of technology standards commonly referred to as AJAX (Asynchronous JavaScript and XML). 

AJAX includes:

Asynchronous requests are initiated by using JavaScript in the browser client to create a new connection to a server.  This includes stateful postbacks to a page or stateless requests to services apart from the current page.  In the case of an asynchronous postback, only the information that needs to be processed by the current page on the server is passed in the request.  Since the contents of the entire page do not need to be submitted, the page lifecycle for a asynchronous postback only calls server events associated with processing and rendering the requested content.   In either case, asynchronous requests are handled by creating explicit connections to a server, which means an end user can continue working in the client application while the request is being processed.  When a response is returned, the appropriate content in the Web page (browser memory) is updated without refreshing the entire page.  The diagrams below illustrate the difference between synchronous and asynchronous communication between a client application and a server.


Synchronous                                                                  

        


Asynchronous

          

AJAX solutions are generally divided into three framework categories: callback, UI and full.  A callback framework consists of a simple set of client and server libraries.   It generally involves invoking methods on a server component and moving input and output parameters in a serialized format.  A UI framework consists of a set of server controls that manage asynchronous postbacks and inject client JavaScript in a page at runtime.  A full framework provides a comprehensive programming model which includes controls, services and public APIs on both the client and the server.  

Microsoft provides two solutions for managing asynchronous postbacks in an ASP.NET 2.0 Web application: a callback framework solution using ASP.NET client callbacks and a full framework solution using ASP.NET AJAX.  

ASP.NET client callbacks

With the release of ASP.NET 2.0, Microsoft introduced client callbacks for simple, lightweight, yet effective AJAX solutions in a Web application.  One interface (ICallbackEventHandler), a client script manager class and a single JavaScript file (WebForms.js) are provided to manage asynchronous communication between client and server.  At runtime, after initial page load, a callback to a page runs a modified version of its normal life cycle (see diagram below) where the page is initiated and loaded, but the page contents are not rendered.   Instead, a single method in the server-side code is invoked, which processes the callback request and returns a value to the browser and can be read by a JavaScript function.  The JavaScript function uses technology inherent to the browser (e.g. DOM, DHTML) to update Web page content dynamically.    While the communication process is extremely lightweight, callbacks do have one significant drawback.   When utilizing a callback solution, Web developers are responsible for providing all the server and client-side code necessary to rerender controls in a browser and manage client-server synchronization.     

ASP.NET AJAX

To provide a more comprehensive AJAX solution Microsoft released ASP.NET AJAX in early 2007.  ASP.NET AJAX provides a complete client-server architecture for developing and deploying AJAX solutions.  The server components include a set of controls and an API to manage the display of and interaction between Web controls and services.   The client component consists of a set of JavaScript libraries (termed the "Microsoft AJAX Library") which manage asynchronous communication with Web applications and services and update browser content dynamically.   Together they operate to synchronize client\server interaction in an asynchronous communication environment without requiring a Web developer to write custom client script to manage events and rendering.       

At a basic level, Microsoft AJAX supports asynchronous requests via a partial page postback.   Partial postbacks iterate through the same page lifecycle as a synchronous full page postback, but only specific regions or controls on the page are refreshed - thus partial page rendering.   ASP.NET AJAX is dependent on the interceptor pattern to generate and handle a partial post back.  Upon initialization, ASP.NET AJAX JavaScript libraries add a set of client event handlers to intercept calls that would normally initiate a full page postback.  The handler functions intercept postback calls from registered controls, generate a partial postback, process response content and update page content asynchronously.   Since ASP.NET AJAX is built on the existing ASP.NET postback architecture it also supports utilizing event validation and maintaining view state in a partial postback communication process.  

While ASP.NET AJAX does provide an extensive architecture, three components are integral to its use: the ScriptManager and UpdatePanel server controls and the PageRequestManager object on the client. 

In general, the ScriptManager enables the use of ASP.NET AJAX within a page.  It provides the Microsoft AJAX Library (MicrosoftAjax.js and MicrosoftAjaxWebForms.js) to the client browser which includes the complex client framework for intercepting postback requests to generate partial postbacks and processing partial postback responses to update page data.   Only one ScriptManager is required per page and it must be the first control in the page.  It is designed to work in conjunction with the PageRequestManager JavaScript object to register controls to initiate partial postbacks or update content, register event handlers, initialize the interceptor pattern, etc.  Only server controls that implement IPostBackEventHandler, IPostBackDataHandler and INamingContainer can initiate a partial postback when registered with the ScriptManager.  During a postback you may want to update (rerender) specific controls and content in the page.  This can be easily achieved using the UpdatePanel control which enables specific portions of a page to be updated during an asynchronous postback.  It can contain any valid page content, such as HTML and server controls.  By default, when a server control in an UpdatePanel initiates a postback, it will generate an asynchronous postback and update the content of the UpdatePanel.  In addition, other server controls in the page (known as triggers) can cause UpdatePanel contents to rerender during an asynchronous postback.  The ScriptManager keeps track of the UpdatePanels on the page and their respective triggers.   When a partial postback is processed on the server, the page and all controls in the page will iterate through their full lifecycle, which includes rendering events.  The ScriptManager will determine which controls to rerender based on the control which initiated the partial postback (a parameter of the request).    In general, any UpdatePanels associated with this control as a trigger and any UpdatePanels with an UpdateMode property set to Always will be rerendered and included in the partial postback response.   Note that every control in the UpdatePanel will be rerendered, even if its state did not change.  

It is important to note that utilizing the partial postback capabilities of ASP.NET AJAX does not require the use of an UpdatePanel - the UpdatePanel merely makes it easier to define sections within a page that may be updated asynchronously via a partial postback.   The ScriptManager provides more fine grained control over partial postback response content by enabling the registration of data items and client script blocks.  However, in both cases some custom JavaScript is required to manage interaction with the data on the client.      

The table below highlights a few differences between ASP.NET client callbacks and ASP.NET AJAX partial postbacks:

Topic ASP.NET client callbacks ASP.NET AJAX partial postbacks
Availability  Included with ASP.NET 2.0. Visual Studio 2005, .NET 2.0: Requires the download and installation of AJAX Extensions.

Visual Studio 2008, .NET 3.5: Includes AJAX Extensions 
Required modifications to a basic ASP.NET Web application  None.
Add a reference to System.Web.Extensions and add custom handlers and services to the Web.config. 
Includes server controls?  No.  Yes. A set of controls to manage client/server registration,  synchronization, and rendering.  
Includes client script? Yes. One file, WebForms.js, included as a WebResource.  The JavaScript functions are merely designed to send and receive a serialized message.  Custom JavaScript code must be created to parse a callback response and update page content.  Cross-browser support must be explicitly created.   Yes. Two files, MicrosoftAjax.js and MicrosoftAjaxWebForms.js, included as ScriptResources.  Both provide cross-browser support for a rich public client API to support working with server components in a script environment.  Includes event handlers, view state maintenance, event validation, and most importantly the logic to update page content asynchronously.  No custom JavaScript code is explicitly required.  Note, the WebForms.js file is also included to support client callbacks within the context of an ASP.NET AJAX Web application.       
Enable on a server control To process a callback, a control must implement ICallbackEventHandler.  To trigger and process a postback (partial or full), a control must implement IPostBackEventHandler, IPostBackDataHandler or INamingContainer. 
Initiate a request Add ClientScript reference to a page and call JavaScript WebForm_DoCallback at runtime. Add a ScriptManager control to a page, then add and register a control with the ScriptManager to generate an asynchronous postback.  Initiate a postback from the control at runtime.
Which control initiated the request? In the callback request, the value of the parameter __CALLBACKID equals the id of the server control associated with the callback (defined in the WebForm_DoCallback function). 

Example syntax:
__CALLBACKID=Page1
In the postback request, the ScriptManager id operates as the parameter.  In general, the value is the id of the control that initiated the partial postback.  It is in the format <id of the control registered to>|<id of the registered control>.  Controls can register with the ScriptManager directly or via an UpdatePanel.   The ScriptManager.AsyncPostBackSourceElementID property will return the id of the control that initiated the partial postback. 

Example syntax:
ScriptManager1=UpdatePanel1|Button1
Generate the response on the server  The control associated with the callback request will generate a custom serialized callback response string.  The control which initiated the postback will dictate which controls will be updated in the postback response.  The rendering methods (e.g. PreRender, Render) generate the control content and a string serialized for ASP.NET AJAX JavaScript libraries is included in the postback response. 
Process the response on the client Since a serialized string in a custom format will be returned to the client, custom JavaScript must be created to explicitly process the string and update the browser client.  The ASP.NET client callback framework does not include any prepackaged JavaScript to process the callback response string. In many cases, ASP.NET AJAX JavaScript will update the browser client without custom code.  Custom controls will often require custom JavaScript. 
Maintains view state and manages event validation? No. Yes.


The diagram below illustrates the difference between the page lifecycle sequence of events between a page postback (synchronous full page postback and asynchronous partial postback) and a client callback.  The Page.IsPostback property will return true for all three request types.  The Page.IsCallback property will return true only when the request is a client callback.  To distinguish between a full and partial postback, the ScriptManager control maintains an IsInAsyncPostBack property.   The property will return true only when the request is a partial postback.  Note that a page can contain only one ScriptManager.  To return the ScriptManager for a given page, use the static ScriptManager.GetCurrent() method and pass the Page object as a parameter.

  

     
Working with AJAX in an ASP.NET Web application

Two walkthroughs are presented below to illustrate the differences between the implementing an ASP.NET AJAX and ASP.NET client callback solution.   A simple example is provide for instructive purposes.  The example involves clicking on a button to trigger an asynchronous request and returning the current time on the Web server to be rendered in the browser client.   A set of steps detailing the implementation and runtime process is provided.  Note that at a basic level, the client callback solution requires more client and server code to implement, but the request/response payload is completely customizable and the page/control lifecycle is shorter when compared to the ASP.NET AJAX solution.    Also, client callbacks can be initiated using pure HTML client elements and server controls.   ASP.NET AJAX partial postbacks are designed to be initiated by server controls.  

Walkthrough: Working with partial postbacks in an ASP.NET Web application

The source code for this walkthrough is included in the SimpleParitalPostback.aspx page in the sample: Common_PartialPostback.

Leveraging ASP.NET AJAX in a ASP.NET 2.0 Web application involves working with a set of AJAX controls and the standard postback model to handle events and manage view state.   The process may involve three steps.  First, install ASP.NET AJAX and create a Web application with the appropriate references.  Second, add and configure AJAX and server controls in the page.  And finally, handle events on controls in the page to update portions of a page asynchronously.  

The following outline highlights the basic steps used to utilize ASP.NET AJAX functionality in a Web page.

  1. Install ASP.NET AJAX.

    If ASP.NET AJAX has already been installed, skip this step.  To install, download and install the ASP.NET 2.0 AJAX Extensions 1.0 msi from http://asp.net/ajax/downloads/.   The setup includes a set of .NET assemblies containing server controls and APIs, a set of JavaScript libraries (the Microsoft AJAX Library), and a web.config. 
  2. Create an ASP.NET Web application that includes ASP.NET AJAX entries in the Web.config file. 

    These entries include references to the System.Web.Extensions and a set of handlers and services.  Visual Studio 2005 provides a template "ASP.NET AJAX-Enabled Web site" which includes these references.  The ASP.NET AJAX setup includes a web.config which can be used to replace the basic web.config generated for a standard ASP.NET Web application.   
  3. Add a ScriptManager control. 

    In the Visual Studio toolbar under the AJAX Extensions tab, drag a ScriptManager control onto the page.  The ScriptManager must be placed in a form tag with runat=server.   It must also be listed before any other controls in the form that require it. 

    Adding a ScriptManager to a page enables the use of ASP.NET AJAX JavaScript libraries at runtime.  When a ScriptManager is present in a page at runtime, at a minimum, three sections will also be included in the page to initialize ASP.NET AJAX JavaScript: references to AJAX JavaScript,  initialization of PageRequestManager, and initialization of the ASP.NET AJAX application components. 
    • ASP.NET AJAX includes an HTTP handler (ScriptResourceHandler) to streamline the distribution of scripts to clients by enabling the ability to compress script content.   Modifications to the web.config (mentioned earlier in this document) to support ASP.NET AJAX expose the handler for use via the root path ScriptResource.axd.  When a ScriptManager is present in a page at runtime, a set of script tags similar to the following will be included:
      <script src="/MyWebsite/ScriptResource.axd?d=-EaodRrAjwRcPF2Gnc0YTNE1ohGg-MHKgQ4-4pRODSHBpzTL_f7ixjpCSIhHG2x_q1Kg2a4Q7LhPzEHqJQOaEpGifN0than184BduvwGeY81&
      t=633251404579172099" type="text/javascript"></script>
      <script src="/MyWebsite/ScriptResource.axd?d=-EaodRrAjwRcPF2Gnc0YTNE1ohGg-MHKgQ4-4pRODSHBpzTL_f7ixjpCSIhHG2x_q1Kg2a4Q7LhPzEHqJQOaEoPWXTHIX55Yb3IV2xe_j-4sb
      m1dKOIjJjgq4yMc1L5C0&t=633251404579172099" type="text/javascript"></script>
      

      Note that the standard ASP.NET WebResource handler is used to include a reference to the script callback library WebForms.js.  It is included with the ScriptManager for convenience.
    • The PageRequestManager works in conjunction with the ScriptManager to register which controls will trigger asynchronous postbacks and which UpdatePanels will update.  PageRequestManager also handles the initialization of the interceptor pattern required for ASP.NET AJAX to handle postbacks asynchronously.  To accomplish this, the following JavaScript calls are included in the page:
      Sys.WebForms.PageRequestManager._initialize('ScriptManager2', document.getElementById('form1'));
      Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1','tUpdatePanel2','tUpdatePanel3'], ['Button1','Button2'], [], 90);
      							
    • ASP.NET AJAX JavaScript components and handlers need to be initialized after the content of the form loads.  To accomplish this, the following JavaScript is included in the page at the bottom of the form in which the ScriptManager resides: 
      Sys.Application.initialize();
      							
    Listed below are a few key members of interest on the ScriptManager control:

    ScriptManager members Description
    Properties  EnablePartialRendering Enables partial rendering of a page, which in turn enables you to update regions of the page individually by using UpdatePanel controls.  By default, this property value is true.
    Methods  RegisterAsyncPostBackControl
    Registers a server control for asynchronous postbacks, which can be used to update specific regions of the page.  This method is used for controls outside of an UpdatePanel control, which would by default perform a synchronous full page postback.  The control must implement IPostBackEventHandler, IPostBackDataHandler, or INamingContainer.  
     RegisterPostBackControl Registers a server control for synchronous full page postback.  This method is used for controls inside an UpdatePanel control that would otherwise perform asynchronous postbacks.  The control must implement IPostBackEventHandler. 

  4. Add an UpdatePanel control. 

    In the Visual Studio toolbar under the Extensions tab, drag an UpdatePanel control onto the page.  Add the UpdatePanel after the ScriptManager control.  Listed below are a few key members of interest on the UpdatePanel control:

    UpdatePanel members Description
    Properties ChildrenAsTriggers Indicates whether postbacks from immediate child controls of an UpdatePanel control update the panel's content.  The default is true.
    Triggers A collection of controls and their events that cause the UpdatePanel control to update upon postback.
    UpdateMode Two options: Always and Conditional.  Always is the default and will cause the UpdatePanel to update upon every postback.  Conditional will only cause the UpdatePanel to update when a trigger (registered or child control) initiates a postback.  
  5. Add a Button and Label (both server controls) in the UpdatePanel.

    Since the Button implements IPostBackEventHandler and is within the UpdatePanel, it will initiate an asynchronous postback upon click.  Set the Text property on the Button to "Get Server Time".
    The page should appear as follows:

        
  6. Handle the click event of the Button and change the Label text.

    Handle the client event of the Button as you would for a traditional postback.  For example, add the in the declarative content of the page, add OnClick attribute and reference a method in the page, Button1_Click.  

    <asp:Button id=Button1 onclick=Button1_Click Text="Get Server Time" runat="server"></asp:Button>
     
    In the event, set the Label1 Text property to the current time on the server. 

    [C#]
    protected void Button1_Click(object sender, EventArgs e)
    {
      Label1.Text = DateTime.Now.ToString();
    }

    The following diagram illustrates an asynchronous postback event to initiate partial rendering of a page at runtime.  The green circles indicate the order in which events occur to initiate and process the postback.  A description for each step is provided below.

 

    1. By default a server control Button is rendered as an HTML input element that submits the form it resides in.  When a ScriptManager is present within a page, all calls to form.submit() or __doPostBack are intercepted by a handler added during Sys.WebForms.PageRequestManager initialization (initial page load).  At runtime these calls, whether synchronous or asynchronous, are redirected to the private function PageRequestManager._onFormSubmit().   In this case, clicking the Button will submit the form and trigger an asynchronous postback since the Button resides in an UpdatePanel.  Controls outside an UpdatePanel need to register with the ScriptManager to initiate an asynchronous postback.  A new AJAX object Sys.Web.WebRequest is created, properties are set and it is invoked.    
    2. When the WebRequest is invoked is uses a Sys.Net.XmlHTTPExecutor to create an XMLHttpRequest object.  The XMLHttpRequest object connects to the server and submits the request.  The request includes a reference to the ScriptManager and the control that initiated the postback, a custom header ("x-microsoftajax"), view state and event validation information.   Here is an example request, note some of the general header information has been excluded:
      POST /MyWebsite/SimplePartialPostback.aspx HTTP/1.1
      x-microsoftajax: Delta=true
      Content-Type: application/x-www-form-urlencoded
      
      ScriptManager1=UpdatePanel1|Button1&__EVENTTARGET= &__EVENTARGUMENT=&
      __VIEWSTATE= %2FwEPDwULLTIxMTM4NzY5MzFkZKNQGsH4q9tpA8BH6b84TcMfi0fV&
      __EVENTVALIDATION=%2FwEWAgK4%2FtfdBQKM54rGBpRqW1kQZkPGexH7%2B3rIj%2BivSiMJ&
      Button1=Get%20Server%20Time
       
      					
    3. On the server, the ScriptManager control manages all page and control rendering via interaction with the ASP.NET AJAX System.Web.UI.PageRequestManager and System.Web.UI.ScriptManager.IPage interface.   The PageRequestManager determine if the postback is asynchronous and initiated by client using ASP.NET AJAX JavaScript.  It looks for the header "x-microsoftajax" to contain the argument\value pair "Delta=true"   If true, the ScriptManager will intercept all page content rendering and generate the HTTP response.  If an UpdatePanel is to be rerendered during the postback, all controls it contains are completely rerendered, even if they did not change.   The first part of the partial postback response contains the raw rerendered content.  The next section includes a set of serialized values to track view state, event validation, asynchronous postback controls, UpdatePanels and triggers.  The final section is optional and includes any custom data items or script includes registered with the ScriptManager during postback processing on the server.  Here is an example response, note some of the general header information has been excluded:
      HTTP/1.1 200 OK
      Server: Microsoft-IIS/5.1 Date: Thu, 08 Nov 2007 01:07:21 GMT
      Content-Type: text/plain; charset=utf-8
      
      172|updatePanel|UpdatePanel1|
      <input type="submit" name="Button1" value="Get Server Time" id="Button1" />
      <span id= "Label1">11/7/2007 5:07:21 PM</span>
      |1e0128|hiddenField|__VIEWSTATE|/ wEPDwULLTIxMTM4NzY5MzEPZBYCAgMPZBYCAgMPZBYCZg9kFgICAw8PFgIeBFRleHQFFDExLzcvMjAwNyA1OjA3OjIxIFBNZGRkYeVef8HDv2pb/77ZnVtAjeVPeVI=
      |48|hiddenField|__EVENTVALIDATION|/wEWAgK18bqfBQKM54rGBoFX9wkAeMuxT4L2336BrKkHwERo|0|asyncPostBackControlIDs|||0|
      postBackControlIDs|||13|updatePanelIDs||tUpdatePanel1|0|childUpdatePanelIDs|||12|panelsToRefreshIDs||UpdatePanel1|2|asyncPostBackTimeout||90|
      26|formAction||SimplePartialPostback.aspx|13|pageTitle||Untitled
      Page|0
      					
    4. The partial postback response is returned to the browser client and processed by the WebRequest which wrapped the initial request.  The body of the response is directed to the PageRequestManager._onFormSubmitCompleted() function by a handler registered with via WebRequest.add_completed function.  The _onFormSubmitCompleted() function contains the logic to parse the body of the response.  The logic is designed to update page elements and view state, execute JavaScript includes, pass data items to their respective handlers, and modify ASP.NET AJAX JavaScript components dynamically. 
            


Walkthrough: Working with client callbacks in an ASP.NET Web application 

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

Developing an ASP.NET 2.0 Web application that uses client callbacks is a two-step process.  First, create the server-side code that will be invoked by the client.  Second, create the client-side code to invoke the callback request and process the response.  Note that the message in the callback request and response is always a string.  The content and format of the string is up to the developer.  The request usually includes a string to tell the server which action to perform and some user provided data.  The response usually contains content to be rendered on the client or a set of data to trigger further actions.

The following outline highlights the basic steps used to implement client callbacks in an ASP.NET 2.0 Web page.  It assumes that you have created a standard, empty ASP.NET Web application.  

  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 can be designed to parse the message and determine 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.   Here is an implementation example of both methods in the code-behind page Default.aspx.cs.  The eventArgument will be updated via a callback request from the client.  This is discussed in greater detail below. 

    [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();
    		}
    	}
    }
  2. Call the GetCallbackEventReference method on the Page class.

    The GetCallbackEventReference method creates a JavaScript string in the client Web page to start the callback.  The usage and method parameters are listed below:

    Usage: GetCallbackEventReference(control, argument, clientCallback, context, clientErrorCallback, useAsync);
    Parameter Name Description
    control The control or the page which implements ICallbackEventHandler.
    argument Name of a client-side JavaScript variable. References the string sent to the RaiseCallbackEvent method via the eventArgument parameter.
    clientCallback Name of the client-side JavaScript function which will receive the result of a successful server event.
    context 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 will be stored on the client as the context parameter associated with a callback.
    clientErrorCallback Name of the client-side JavaScript function which will receive the callback result when an error occurs.
    useAsync Boolean to determine whether a synchronous or asynchronous callback is made to the server.

    Here is an example of the method used in code.  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 parameters listed above.  The next step will discuss adding a reference to this function in client-side code. 
  3. Create the client-side code to trigger the callback and process the response.

    Implementing System.Web.UI.ICallbackEventHandler and calling GetCallbackEventReference will add a line similar to the following script tag in your aspx page at runtime:
    <script src="/MyWebsite/WebResource.axd?d=TqQApA1CcEIyShhLjzTczw2&t=632657807109074470" type="text/javascript">
    </script>
    
    WebResource.axd is a HTTP Handler included with ASP.NET 2.0 that 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 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 timestamp for the requested assembly, which can help in determining 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.   The JavaScript function which initiates and manages callbacks in the client browser is WebForm_DoCallback.  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 XML Document Object Model, part of the MSXML set of components.     

    The following code provides an example of the HTML content in an aspx page configured to work with callbacks.  The edits to the code involve two steps:

    1. Add an HTML element and a JavaScript function to create a callback request.  In the HTML code below, the click event of an HTML button triggers a call to the JavaScript function getServerTime, which in turn calls WebForm_DoCallback.  The message variable is set to 'getservertime' which is used by the server to determine which action to execute.  The server variable <%=sCallBackFunctionInvocation%> 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.  Note, this happens dynamically so other objects in the page are not redrawn.  The postMyError function receives the callback message if an error was thrown on the server.  In this case, it pops up an alert box.
    <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 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 short description for each step is provided below:


     


    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\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 some 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.