Working with AJAX and ASP.NET


Summary
Interaction with a Web application can be initiated via a synchronous or asynchronous request from the client to the server. This topic discusses both options.

In this topic


Synchronous requests

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 a Hypertext Markup Language (HTML) form. A postback 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.
The following illustration shows synchronous communication between a client application and a server:

Asynchronous requests

Asynchronous requests can improve performance and enhance the end-user experience when working with a Web application. Asynchronous requests utilize the Asynchronous JavaScript and XML (AJAX) technology standard.
AJAX includes the following:
  • Presentation content using Extensible Hypertext Markup Language (XHTML) and Cascading Style Sheets (CSS)
  • Dynamic display and interaction with XHTML (Dynamic HTML [DHTML]) using the Document Object Model (DOM)
  • Data interchange using strings, often in Extensible Markup Language (XML) format
  • Asynchronous data retrieval using a Hypertext Transfer Protocol (HTTP) request object (the 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 life cycle for an 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 following illustration shows asynchronous communication between a client application and a server:

AJAX solutions

AJAX solutions are generally divided into the following framework categories:
  • Callback—Consists of a simple set of client and server libraries. A callback framework usually involves invoking methods on a server component, and moving input and output parameters in a serialized format.
  • UI—Consists of a set of server controls that manage asynchronous postbacks and inject client JavaScript in a page at runtime.
  • Full—Provides a comprehensive programming model that includes controls, services, and public application programming interfaces (APIs) on both the client and the server.
Microsoft provides the following solutions for managing asynchronous postbacks in an ASP.NET 2.0 Web application:
  • Callback framework solution using ASP.NET client callbacks
  • 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. In the ICallbackEventHandler interface, 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 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, returns a value to the browser, and can be read by a JavaScript function. The JavaScript function uses technology inherent to the browser (for example, DOM and DHTML) to update Web page content dynamically.
While the communication process is 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 render controls again in a browser and manage client-server synchronization.

ASP.NET AJAX partial postbacks

To provide a more comprehensive AJAX solution, Microsoft released ASP.NET AJAX. 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 (called the Microsoft AJAX Library) that 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 life cycle as a synchronous full page postback, but only specific regions or controls on the page are refreshed (partial page rendering). ASP.NET AJAX is dependent on the interceptor pattern to generate and handle a partial postback. Upon initialization, ASP.NET AJAX JavaScript libraries add a set of client event handlers to intercept calls that 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 provides an extensive architecture, the following components are integral to its use:
  • ScriptManager server control
  • UpdatePanel server control
  • PageRequestManager object on the client
In general, the ScriptManager enables the use of ASP.NET AJAX on 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 as well as for processing partial postback responses to update page data.
Only one ScriptManager is required per page and it must be the first control on the page. The ScriptManager works in conjunction with the PageRequestManager JavaScript object to register controls to initiate partial postbacks or update content, register event handlers, initialize the interceptor pattern, and so on. Only server controls that implement IPostBackEventHandler, IPostBackDataHandler, and INamingContainer can initiate a partial postback when registered with the ScriptManager.
During a postback, you can update (render again) specific controls and content in the page by using the UpdatePanel control, which enables specific portions of a page to be updated during an asynchronous postback. The UpdatePanel control 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 generates an asynchronous postback and updates the content of the UpdatePanel. In addition, other server controls on the page (known as triggers) can cause UpdatePanel contents to render again 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 the controls on the page, iterate through their full life cycle, which includes rendering events. The ScriptManager determines which controls to render again based on the control that 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 are rendered again and included in the partial postback response.
Each control in the UpdatePanel is rendered again, even if its state did not change.
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 on a page that can 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. In both cases, however, custom JavaScript is required to manage interaction with the data on the client.

Differences between client callbacks and partial postbacks

The following table describes differences between ASP.NET client callbacks and ASP.NET AJAX partial postbacks:
 Subject
ASP.NET client callback
ASP.NET AJAX partial postback
Availability
Included with ASP.NET 2.0.
Visual Studio 2005, .NET 2.0: Requires 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 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, is included as a WebResource. The JavaScript functions 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, are included as ScriptResources. Both provide cross-browser support for a public client API to support working with server components in a script environment. Includes event handlers, view state maintenance, event validation, and the logic to update page content asynchronously. No custom JavaScript code is explicitly required.
 
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 __CALLBACKID parameter 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 <id of the control registered to>|<id of the registered control> format. Controls can register with the ScriptManager directly or via an UpdatePanel. The ScriptManager.AsyncPostBackSourceElementID property returns the id of the control that initiated the partial postback.
 
See the following example syntax:
ScriptManager1=UpdatePanel1|Button1
Generate the response on the server
The control associated with the callback request generates a custom serialized callback response string.
The control that initiated the postback dictates the controls that are updated in the postback response. The rendering methods (for example, 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 is 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 prepackaged JavaScript to process the callback response string.
In many cases, ASP.NET AJAX JavaScript updates the browser client without custom code. Custom controls often require custom JavaScript.
Maintains view state and manages event validation?
No.
Yes.
The following illustration shows the differences between the page life cycle sequence of events of a page postback (synchronous full page postback and asynchronous partial postback) and a client callback:
  
The Page.IsPostback property returns true for all three request types. The Page.IsCallback property returns true only when the request is a client callback. To distinguish between a full and partial postback, the ScriptManager control maintains the IsInAsyncPostBack property. This property returns true only when the request is a partial postback.
A page can contain only one ScriptManager. To return the ScriptManager for a page, use the static ScriptManager.GetCurrent() method and pass the Page object as a parameter.

AJAX in ASP.NET Web applications

For more information about working with AJAX in an ASP.NET Web application, see the following topics:
The preceding referenced topics discuss the differences between implementing an ASP.NET AJAX solution and implementing an ASP.NET client callback solution.
How to work with partial postbacks in an ASP.NET Web application is a simple example of how clicking a button can trigger an asynchronous request and return the current time on the Web server to be rendered in the browser client. Steps detailing the implementation and runtime process are provided.
At a basic level, the client callback solution topic, How to work with client callbacks in an ASP.NET Web application, requires more client and server code to implement, but the request and response payload is completely customizable, and the page and control life cycles are 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 initiated by server controls.


See Also:

AJAX capabilities in the Web ADF
Working with callback results
ASP.NET AJAX partial postback solutions
How to work with partial postbacks in an ASP.NET Web application
How to work with client callbacks in an ASP.NET Web application