You are on page 1of 24

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:

• Presentation content using XHTML and CSS

• Dynamic display and interaction with XHTML (DHTML) using the Document Object Model (DOM)

• Data interchange using strings, often in XML format

• Asynchronous data retrieval using an http request object (XMLHttpRequest object)

• JavaScript - to bind everything together

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 None. Add a reference to System.Web.Extensions and add custom handlers and services to the Web.config.
ASP.NET Web application

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. Yes. Two files, MicrosoftAjax.js and MicrosoftAjaxWebForms.js, included as ScriptResources. Both provide cross-browser support for
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 a rich public client API to support working with server components in a script environment. Includes event handlers, view state maintenance
update page content. Cross-browser support must be
explicitly created. , 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 To trigger and process a postback (partial or full), a control must implement IPostBackEventHandler, IPostBackDataHandler or
ICallbackEventHandler.
INamingContainer.

Initiate a request Add ClientScript reference to a page and call JavaScript Add a ScriptManager control to a page, then add and register a control with the ScriptManager to generate an asynchronous postback
WebForm_DoCallback at runtime.
. Initiate a postback from the control at runtime.

Which control initiated the request? In the callback request, the value of the parameter In the postback request, the ScriptManager id operates as the parameter. In general, the value is the id of the control that initiated the
__CALLBACKID equals the id of the server control
associated with the callback (defined in the partial postback. It is in the format <id of the control registered to>|<id of the registered control>. Controls can register with the
WebForm_DoCallback function).
ScriptManager directly or via an UpdatePanel. The ScriptManager.AsyncPostBackSourceElementID property will return the id of the
Example syntax: control that initiated the partial postback.
__CALLBACKID=Page1
Example syntax:
ScriptManager1=UpdatePanel1|Button1

Generate the response on the server The control associated with the callback request The control which initiated the postback will dictate which controls will be updated in the postback response. The rendering methods
will generate a custom serialized callback response
string. (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 In many cases, ASP.NET AJAX JavaScript will update the browser client without custom code. Custom controls will often require custom
returned to the client, custom JavaScript must be created
to explicitly process the string and update the browser JavaScript.
client. The ASP.NET client callback framework does not
include any prepackaged JavaScript to process the
callback response string.

Maintains view state and manages No. Yes.


event validation?

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.
o 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:

o <script src="/MyWebsite/ScriptResource.axd?d=-EaodRrAjwRcPF2Gnc0YTNE1ohGg-MHKgQ4-
4pRODSHBpzTL_f7ixjpCSIhHG2x_q1Kg2a4Q7LhPzEHqJQOaEpGifN0than184BduvwGeY81&

o t=633251404579172099" type="text/javascript"></script>

o <script src="/MyWebsite/ScriptResource.axd?d=-EaodRrAjwRcPF2Gnc0YTNE1ohGg-MHKgQ4-
4pRODSHBpzTL_f7ixjpCSIhHG2x_q1Kg2a4Q7LhPzEHqJQOaEoPWXTHIX55Yb3IV2xe_j-4sb

o 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.

o 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:

o Sys.WebForms.PageRequestManager._initialize('ScriptManager2', document.getElementById('form1'));

o Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1','tUpdatePanel2','tUpdatePanel
3'], ['Button1','Button2'], [], 90);
o 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:

o Sys.Application.initialize();

4. 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.

5.
6. 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.

7. 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:

8. 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.

9. <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:

3. POST /MyWebsite/SimplePartialPostback.aspx HTTP/1.1

4. x-microsoftajax: Delta=true

5. Content-Type: application/x-www-form-urlencoded

6.

7. ScriptManager1=UpdatePanel1|Button1&__EVENTTARGET= &__EVENTARGUMENT=&
8. __VIEWSTATE= %2FwEPDwULLTIxMTM4NzY5MzFkZKNQGsH4q9tpA8BH6b84TcMfi0fV&

9. __EVENTVALIDATION=%2FwEWAgK4%2FtfdBQKM54rGBpRqW1kQZkPGexH7%2B3rIj%2BivSiMJ&

10. Button1=Get%20Server%20Time

11.

12. 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:

13. HTTP/1.1 200 OK

14. Server: Microsoft-IIS/5.1 Date: Thu, 08 Nov 2007 01:07:21 GMT

15. Content-Type: text/plain; charset=utf-8

16.

17. 172|updatePanel|UpdatePanel1|

18. <input type="submit" name="Button1" value="Get Server Time" id="Button1" />

19. <span id= "Label1">11/7/2007 5:07:21 PM</span>

20. |1e0128|hiddenField|__VIEWSTATE|/
wEPDwULLTIxMTM4NzY5MzEPZBYCAgMPZBYCAgMPZBYCZg9kFgICAw8PFgIeBFRleHQFFDExLzcvMjAwNyA1OjA3OjIxIFBNZGRkYeVef8HDv2p
b/77ZnVtAjeVPeVI=

21. |48|hiddenField|__EVENTVALIDATION|/wEWAgK18bqfBQKM54rGBoFX9wkAeMuxT4L2336BrKkHwERo|0|
asyncPostBackControlIDs|||0|

22. postBackControlIDs|||13|updatePanelIDs||tUpdatePanel1|0|childUpdatePanelIDs|||12|panelsToRefreshIDs||
UpdatePanel1|2|asyncPostBackTimeout||90|

23. 26|formAction||SimplePartialPostback.aspx|13|pageTitle||Untitled

24. Page|0
25. 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,
Parameter Name Description useAsync);
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. Here is an example of the method used in code. The
sCallBackFunctionInvocation member variable is a public
clientCallback Name of the client-side JavaScript function which will receive the result of a successful server event.
string, global to the Page class:

context Name of a client-side JavaScript variable. Usually used to determine the content of the message [C#]
(argument) in the callback request. The value of the variable will be stored on the client as the context
parameter associated with a callback.
public string sCallBackFunctionInvocation;
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.

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:

4. <script src="/MyWebsite/WebResource.axd?d=TqQApA1CcEIyShhLjzTczw2&t=632657807109074470"
type="text/javascript">

5. </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:

a. 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.

b. 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.
Working with AJAX capabilities of the Web ADF

ASP.NET supports both synchronous and asynchronous communication with Web applications. The Web ADF controls are designed leverage two AJAX patterns
packaged for use with ASP.NET: ASP.NET script callbacks and ASP.NET AJAX. Both are provided by Microsoft to enhance the Web application developer and user
experience. It is recommended that you are familiar with AJAX and ASP.NET technologies and concepts before proceeding.

As a Web ADF developer, you have the option to select which AJAX pattern you will utilize in your Web application. In version 9.2, the Web ADF only supported the
ASP.NET script callback framework. As a result, many existing applications have been built on the callback model for asynchronous communication. This model
remains valid and supported in 9.3. However, the 9.3 Web ADF also supports the latest Microsoft AJAX solution, ASP.NET AJAX. The Web ADF controls are only
designed to use one model for asynchronous communication per page. The presence of an ASP.NET AJAX ScriptManager control in a page dictates which model will
be used. If a ScriptManager is present, Web ADF controls will use the ASP.NET AJAX partial postback model. If a ScriptManager is not present in the page, the Web
ADF controls will use the ASP.NET script callback model. Note, the ScriptManager must be the first control in the page.

ASP.NET AJAX provides both a client and server side solution. In all cases, Web ADF client-side JavaScript libraries use ASP.NET AJAX client-side JavaScript libraries
to provide a foundation for a comprehensive scriptable environment for AJAX solutions within a browser. On the server, Web ADF components have the option of
utilizing ASP.NET AJAX components and their framework to work with the partial postback pattern.

In many cases, working with AJAX capabilities in the Web ADF will differ depending on which AJAX solution you choose. However, there are some common
components and concepts shared by both. In general, any client-server interaction in the Web ADF will involve an action request and response, followed by
subsequent asynchronous requests to handle changes made during the initial postback. In most cases, an action request is initiated by a user action in the browser
(e.g. zooming in on a map). If the action request is sent to the current page, it may be a synchronous full postback, an asynchronous partial postback, or a callback
(also a type of postback).

Each postback to a page in a Web application will iterate through the page lifecycle. The type of postback will dictate the which lifecycle events are triggered and the
response content. Subsequent requests can be asynchronous and may iterate through the page lifecycle or just request a remote resource, like an image. As a
result, a single user action in the browser may generate multiple requests, some of which iterate through the page lifecycle. For a postback to a page, iterating
through the page lifecycle is required because the page and its contents must be reconstructed to process a request.

Regardless of which Microsoft AJAX pattern is used, the Web ADF includes an internal framework to synchronize changes to the state of client and server content in
an asynchronous environment. This framework, termed the "callback result framework", is founded on Web ADF "callback results" which are messages generated on
the server to communicate changes with the client. The following logical areas in the Web ADF are integral to leveraging the callback result framework and Microsoft
AJAX solutions. As a developer, you can utilize one or more of these component areas to create and manage custom Web ADF AJAX solutions.

• JavaScript libraries to manage postbacks on the client

In version 9.2, the Web ADF included a set of JavaScript libraries built on the ASP.NET callback framework JavaScript. In addition, the Web ADF JavaScript
was not designed to be utilized publicly or customized. In 9.3 this has changed. The ASP.NET AJAX JavaScript libraries have been leveraged to enhance Web
ADF capabilities with a public Web ADF JavaScript Library . As a result, Web ADF applications can take advantage of pure client scripting solutions to enhance
the usability and performance of the application. The ASP.NET AJAX JavaScript libraries are utilized regardless of the AJAX solution used on the server (for
example, even when using the callback model). This is possible because the AJAX Control Toolkit is included with the Web ADF. The AJAX Control Toolkit,
packaged as a single assembly, provides a consistent, Microsoft supported, public platform on which to deploy ASP.NET AJAX solutions. It includes the core
client and server components included with ASP.NET AJAX (Extensions) as well as other components to support the usability and distribution of Web solutions
built on ASP.NET AJAX.

By default, the Web ADF JavaScript Library consists of a set of JavaScript files, embedded as resources with the Web ADF controls. Only those JavaScript
files required to support the Web ADF controls in the application are streamed to the browser client.

From response perspective, the ESRI.ADF.System.processCallbackResult function is most important. Most Web ADF controls generate callback results when
their state changes on the server. The ESRI.ADF.System.processCallbackResult function is designed to parse and process callback results from Web ADF
controls and update their content, at runtime, on the client.

• Tool/command interfaces accessed via a Toolbar control to easily process callbacks on the server
The Toolbar control provides a prepackaged framework for adding client-side tools to interact with Web ADF controls. You only need to create a class on the
server that implements the appropriate interface (depending on the type of toolbar item) and add that class to the Toolbar. Implementation code in the
toolbar item class can interact and change any server-side resource and the postback is managed for you. This is the easiest way to tap into the AJAX
capabilities of the Web ADF, but requires you to work within the context of a Toolbar control.

• Public callback properties on each Web ADF control

All Web ADF controls implement the System.Web.UI.ICallbackEventHandler and System.Web.UI.IPostBackEventHandler interfaces handle asynchronous
requests and generate responses. When a Web ADF control is modified on the server, it generates a response to tell the client how to update the
control. To do this, each Web ADF control maintains a CallbackResults property. The CallbackResults property stores a collection of callback results the
control will send to the client browser to be processed by the processCallbackResult() function. Callback results are messages serialized using JSON ,
JavaScript Object Notation, an efficient, human-readable, data exchange format. If you want to interact with a Web ADF control apart from the
Toolbar control and toolbar items, you often will need to retrieve messages from the CallbackResults property and return them to the client. When
implementing ICallbackEventHandler to support the callback model, messages are returned from the GetCallbackResult() method. When implementing
IPostBackEventHandler to support the partial postback model, messages are added as data items to a ScriptManager in the RaisePostBackEvent() method.

• Custom classes to create and manage callback messages

The CallbackResults property on a Web ADF control returns a CallbackResultCollection. This collection can be modified to include custom CallbackResult
objects. Custom CallbackResult objects can be used to interact with non-Web ADF content in the Web page (e.g. HTML table, GridView, images, text). The
main benefit being that you can use the existing Web ADF JavaScript libraries to change non-Web ADF content on the client instead of writing your
own JavaScript.

Choosing which AJAX solution works for you depends on business rules, application requirements, and technical expertise. Both ASP.NET script callbacks and
ASP.NET AJAX are supported equally. In either case, is important to understand the content and capabilities of the Web ADF callback results framework. It is
discussed in detail in the topic Working with CallbackResults . Once you decide which AJAX solution you will use with Web ADF controls in a Web page,
underlying techniques for working the AJAX capabilities of the Web ADF will differ. This includes the techniques for packaging callback results in an
asynchronous Web response. Each AJAX pattern is presented in a separate topic: ASP.NET callback solutions and ASP.NET AJAX partial postback solutions .

ASP.NET AJAX partial postback solutions

This document provides a detailed discussion on utilizing and extending AJAX capabilities of the Web ADF in an ASP.NET partial postback solution. The content builds
on information presented in a general discussion of AJAX and ASP.NET and an introduction to AJAX capabilities in the Web ADF . It is recommended that you are
familiar with the technologies and concepts presented in both documents before proceeding.

Web ADF controls utilize Microsoft ASP.NET AJAX client and server libraries for all AJAX solutions. The level to which ASP.NET AJAX is utilized depends on which
postback model is leveraged in a Web page. Client implementation for both postback models is the same - Web ADF JavaScript builds on the ASP.NET AJAX
JavaScript Library to provide pure client scripting capabilities and client-server synchronization. Server implementation determines how client-
server synchronization is achieved. For Web ADF partial postback solutions, Web ADF server controls build on ASP.NET AJAX server controls and capabilities to
manage the asynchronous exchange of data via a partial page postback. Web ADF controls will use the partial postback solution if the ASP.NET AJAX ScriptManager
control is present in the same page. With this in mind, two characteristics of ASP.NET AJAX are important to understand from the perspective of the Web ADF.
First, controls that initiate a partial postback are called triggers, must implement IPostBackEventHandler, IPostBackDataHandler or INamingContainer and must be
registered with a ScriptManager. And second, partial updates to page content can be managed using ASP.NET AJAX UpdatePanel controls, data items, or script
blocks. Note, the ScriptManager must be the first control in the page.

At a minimum, all Web ADF controls implement IPostBackEventHandler and register themselves with the current ScriptManager in the page, and thus by default can
trigger a partial postback. When a Web ADF control triggers a partial postback, Web ADF JavaScript uses the ASP.NET AJAX JavaScript Library to add an event
handler. The JavaScript event handler will listen for the page loading event for the duration of the postback. During postback processing on the server, updates to
Web ADF controls are managed by adding CallbackResults as data items to the partial postback response. When the response is returned to the client browser,
the page loading event handler processes the data items and updates Web ADF content. Note that the logic to update Web ADF controls is included with both the
Web ADF JavaScript and server control implementation.

UpdatePanels and Web ADF controls

The ASP.NET AJAX UpdatePanel control provides a convenient means for triggering updates and updating page content via an asynchronous partial
postback. Postbacks triggered by Web controls in an UpdatePanel are asynchronous partial postbacks by default. In addition, Web controls outside an UpdatePanel
can trigger an asynchronous postback to update all content inside an UpdatePanel. If outside an UpdatePanel, controls must explicitly register with the
ScriptManager to trigger a partial postback. The following code illustrates how this registration may occur during the page load event for an ASP.NET Button control
with the id "Button1":

[C#]

protected override void OnLoad(EventArgs e)

base.OnLoad(e);

ScriptManager scriptManager1 = ScriptManager.GetCurrent(Page);

if (scriptManager1 != null)

scriptManager1.RegisterAsyncPostBackControl(Button1);

Web ADF JavaScript and server control implementations already include the logic necessary to register with the ScriptManager, trigger postbacks and update content
within a partial postback solution. As a result, Web ADF controls do not require the use of an UpdatePanel. Web ADF controls will function within an UpdatePanel
and operate as a trigger to update content in an UpdatePanel. However, using a Web ADF control within an UpdatePanel can be very inefficient, and thus is not
recommended for optimum performance. The reason for this inefficiency is the technique used by the UpdatePanel to update content. During a partial postback,
content in an UpdatePanel is completely rerendered. As a result, the rerendered content of a Web ADF control will be returned to the browser, which includes the
HTML content, JavaScript references, and JavaScript function calls. When outside an UpdatePanel, Web ADF controls operate with optimum efficiency. During a
partial postback, Web ADF CallbackResults are generated on the server, serialized to JSON, and registered with a ScriptManager as data items. On the client,
Web ADF specific data items are processed by Web ADF JavaScript and control content is updated. Thus, instead of completely rerendering of a Web ADF control,
very specific updates are defined within the context of ASP.NET AJAX data items. The partial postback scenarios listed below build on this architecture to create an
efficient custom solution.

Custom Partial Postback Scenarios


There are two scenarios you may choose from to customize the Web ADF and utilize its implementation of the ASP.NET AJAX partial postback model. In both
scenarios, the Web ADF CallbackResult and CallbackResultCollection classes are integral to synchronizing changes to Web ADF controls on the server with the client
browser.

1) Web ADF components initiate the partial postback


The diagram below illustrates how a Web ADF control on the client (rendered using HTML\JavaScript in the client browser) initiates a partial postback request, a Web
ADF control handles the postback on the server which generates one or more Web ADF CallbackResults, then the ASP.NET AJAX library processes the partial
postback and calls a event handler added by Web ADF JavaScript to parse Web ADF CallbackResults as data items in the response. The most important point here is
that the Web ADF control that initiated the partial postback will return information that can be used to update itself and other content in the page. The Web ADF
control (the trigger in this situation) maintains a collection of Web ADF CallbackResults which will be included in the partial postback response generated by the
ASP.NET AJAX ScriptManager control. The CallbackResults collection can include CallbackResult instances from three sources. One, the trigger itself will generate
CallbackResults. Two, custom CallbackResults can be created and added to the trigger's CallbackResults collection. And three, the CallbackResults collections for
other Web ADF controls can be copied to the trigger's CallbackResults collection. There is one exception in this situation. CallbackResults generated by Web ADF
controls which maintain a property relationship with the trigger will be added automatically. For example, assume a page contains a Map and Toc control where the
Toc control is buddied with the Map. At runtime, a user action on the Map causes a scale change which changes the visibility of a layer in the Map and Toc. When
the partial postback response is generated, the CallbackResults collection for the Map (the trigger in this case) will also include CallbackResults for the Toc, thus both
will be included in the response. As a developer, you did not need to copy CallbackResults from the Toc to the Map, instead the Web ADF architecture did it for you.
In general, the Web ADF control overview diagram provides a general guide to potential relationships between Web ADF controls. Note, in this scenario, the
trigger's CallbackResults collection will be registered as a data item with the ScriptManager control and processed using Web ADF JavaScript on the client for you - no
explicit work is required on your part as the developer to add a client event handler or register CallbackResults as data items on the server.

This is most common scenario for leveraging Web ADF AJAX capabilities - it includes the pattern for creating custom toolbar items that execute server-side logic using
the Web ADF Toolbar architecture. When using the Web ADF Toolbar, CallbackResults included in the partial postback are managed for you, so it's relatively easy
to incorporate and execute custom code solutions in a Web ADF without explicitly creating or managing client or server side components. Walkthrough #1 below
demonstrates this scenario.
This scenario also includes working with events on Web ADF controls. When a Web ADF control initiates a partial postback, event handlers on Web ADF controls may
generate CallbackResults to reflect changes in the control. CallbackResults associated with the Web ADF control that initiated the partial postbackthe event
occurred will automatically be included in the partial postback. Changes to other controls or browser content can be packaged with the partial postback by adding
Web ADF control CallbackResults or custom CallbackResults to the Web ADF control acting as the trigger for the postback. Walkthrough #3 below demonstrates this
scenario.

2) Non-Web ADF components initiate the partial postback

The diagram below illustrates how to work with Web ADF controls when a partial postback is generated by non-Web ADF content in the browser. There are three
options for updating Web ADF content: UpdatePanels, data items, and dynamic script blocks. All options are standard patterns available for ASP.NET AJAX
solutions. Web ADF controls can reside within UpdatePanels and operate successfully. When the UpdatePanel is updated during a partial postback, it's contents are
completely rerendered. Since Web ADF controls include a JavaScript API to synchronize updates between client and server, updating Web ADF controls within an
UpdatePanel is unnecessary and inefficient. In essence, all Web ADF controls need to be updated on the client are the CallbackResults they generate on the server.
All CallbackResults are processed via the Web ADF JavaScript function ESRI.ADF.System.processCallbackResult(). CallbackResults can be inserted into the partial
postback response as data items or dynamic script blocks.

Dynamic script blocks

The ASP.NET AJAX ScriptManager permits registering a block of JavaScript, constructed on the server, to be executed on the client. Any valid JavaScript can be
included in the script block. For Web ADF controls, the script block will merely call the ESRI.ADF.System.processCallbackResult() function and pass a collection
of Web ADF CallbackResults as an input parameter. Note, an UpdatePanel must be present in the page to use dynamic script blocks. The UpdatePanel can be empty.

The example code below is executed on the server during a user action, such as a Button click or DropDownList item select. The extent for a Web ADF Map control
is set, which generates one or more CallbackResults, stored by the Map via the CallbackResults property. The ToString() method on all Web ADF controls has been
overridden to return the respective control's CallbackResults as a JSON serialized string (thus a call to ToString() is not necessary). All Web ADF CallbackResults can
be packaged in a single CallbackResult collection, before being converted to a string and included in the script block. For example, if another Web ADF control
changed during the postback or a custom CallbackResult was created, merely copy or add the CallbackResults to the Map. Also, note that if you are a server control
developer, and you want to create a control that works for both callbacks and partial postbacks you can check if a ScriptManager is present on the page using the
GetCurrent() static method and return an instance. If you are a page developer, you will know when a ScriptManager is on the page and you will know its id,
thus interrogating the page for a ScriptManager is unnecessary.

[C#]

. . .

string jsProcessCallbackResult = string.Format("ESRI.ADF.System.processCallbackResult('{0}');",

Map1.CallbackResults.ToString().Replace("\\", "\\\\"));

ScriptManager.RegisterClientScriptBlock(Page, sender.GetType(), "changeextent",

string.Format(jsProcessCallbackResult, Map1.CallbackResults), true);

[VB.NET]
. . .

Dim jsProcessCallbackResult As String = String.Format("ESRI.ADF.System.processCallbackResult('{0}');",

Map1.CallbackResults.ToString().Replace("\", "\\"))

ScriptManager.RegisterClientScriptBlock(Page, sender.GetType(), "changeextent", String.Format(jsProcessCallbackResult,

Map1.CallbackResults), True)

You'll notice a Replace statement to change the escape characters in ADF callback results. This is a limitation of dynamically executed JavaScript, a characteristic f a
client script block, and JSON, a format used by callback results. It does not affect strings passed to JavaScript functions on the client, as presented in the
next option, data items. Note, the escape sequence is different for C# and VB.NET.

This technique does present a number of benefits. One, Web controls do not need to be completely rerendered, as is the case with an UpdatePanel. And two, no
custom client-side code is necessary to process the Web ADF CallbackResults. One potential drawback is that all registered script blocks will persist in browser
memory. As a result, the amount of content in a script block, the number of script blocks and the expected duration of a browser session may cause browser
memory to reach an unacceptable limit.

Data items

The ASP.NET AJAX ScriptManager permits registering items of data, packaged as strings on the server and processed on the client. The strings may be formatted
using JSON. Since Web ADF CallbackResults are formatted using JSON, they can easily be packaged as a data item and included in a partial postback
response. The ASP.NET AJAX client API (JavaScript library) includes the ability to manage event handlers on client-side JavaScript objects. One object type, the
PageRequestManager class, manages partial page updates in the browser and maintains a pageLoading event, which is raised after the response from the server to
an asynchronous postback is received but before any content on the page is updated. The pageLoading event can be used to capture data item content included in a
partial postback response for use in the client browser. These two steps and some sample code is provided below to illustrate this technique:

1) Register Web ADF CallbackResults as a data item on the server

During a partial postback on the server, register a data item. The first parameter to the RegisterDataItem() method is the control associated with the item. In this
case, the Page is used because it provides a generic high-level control by which any Web ADF CallbackResults can be registered. Note, that the use of the Page
control is arbitrary, any unique string can be used. The second parameter is the data item string itself. Web ADF CallbackResults are JSON formatted
strings designed to be processed by the Web ADF JavaScript function ESRI.ADF.System.processCallbackResult(). As a result, the string representation of
a CallbackResults collection should be provided as the second parameter to the function. The third parameter defines whether the data item is JSON serialized. If
the data item is a JSON serialized string (true) it's designed to be executed directly within the browser as dynamic JavaScript. If the data item will be used as a
string, such as passed as a parameter to a function, it will not be a JSON serialized string. In this case, callback results are a JSON formatted string designed to be
passed to the ESRI.ADF.System.processCallbackResult() function.

[C#]

ScriptManager1.RegisterDataItem(Page, Map1.CallbackResults.ToString(), false);


2) Add a custom JavaScript function to process the CallbackResults on the client and send them to the processCallbackResults() function.

The JavaScript content can be inserted into a page manually at design-time after the form containing the ScriptManager control is loaded or injected into the page as
a startup script using server-side code. In the example below, the JavaScript has been inserted in the body of the page, after the closing form tag. The code will
add a new event handler function for the page loading event and retrieve the data items based on a unique id (in this example, the client id of the Page). In this
case, the data item is string representing a callback result collection. It is passed directly to the ESRI.ADF.System.processCallbackResult() function.

[JavaScript]

<script>

Sys.Application.add_init(onInitFunction);

// Called once during application initialization

function onInitFunction()

Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(AsyncResponseHandler);

// Called whenever a response to a partial postback is processed on the client

function AsyncResponseHandler(sender, args)

var dataItems = args.get_dataItems();

if (dataItems['__Page'] != null)

ESRI.ADF.System.processCallbackResult(dataItems['__Page']);

</script>
Utilizing data items is a common scenario for developers who want to interact with Web ADF controls when partial postbacks are triggered by non-Web ADF controls
in the page.

Walkthroughs
To interact with Web ADF controls and capabilities via an ASP.NET AJAX partial postback on the server, you have two options. If the Web ADF control triggers the
partial postback, use the existing Web ADF Toolbar framework or implement your own solution to manage CallbackResults via the collection on the Web ADF control
trigger. If a non-Web ADF control triggers the partial postback, you must provide a mechanism for packaging and directing CallbackResults to the appropriate Web
ADF JavaScript function. In addition, you can leverage the Web ADF to update non-Web ADF content in the page without completely rerendering the content (as in
an UpdatePanel) or writing any custom JavaScript code.

<walkthroughs unavailable at this time>

You might also like