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


Summary This topic shows how to use a button to trigger an asynchronous request and to return the current time on the Web server to be rendered in the browser client. Steps detailing the implementation and runtime process of this example of working with partial postbacks in an ASP.NET Web application are provided.

In this topic


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

About working with partial postbacks in an ASP.NET Web application

Leveraging ASP.NET Asynchronous JavaScript and XML (AJAX) in an 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 can involve the following steps:
  1. Install ASP.NET AJAX and create a Web application with the appropriate references
  2. Add and configure AJAX and server controls on the page
  3. Handle events on controls on the page to update portions of a page asynchronously

Utilizing ASP.NET AJAX functionality in a Web page

Perform the following steps to use a button to trigger an asynchronous request and to return the current time on the Web server to be rendered in the browser client:
  1. Install ASP.NET AJAX. If ASP.NET AJAX is already installed, go to step 2.
    To download and install ASP.NET 2.0 AJAX Extensions 1.0, go to http://asp.net/ajax/downloads/. The setup includes a set of .NET assemblies containing server controls and application programming interfaces (APIs), a set of JavaScript libraries (the Microsoft AJAX Library), and a web.config file.
  2. Create an ASP.NET Web application that includes ASP.NET AJAX entries in the web.config file. These entries include references to System.Web.Extensions and a set of handlers and services. Visual Studio 2005 provides a template called ASP.NET AJAX-Enabled Web site that includes these references. The ASP.NET AJAX setup includes a web.config file that can be used to replace the basic web.config file generated for a standard ASP.NET Web application.
  3. Add a ScriptManager control.
    1. In the Visual Studio toolbar under the AJAX Extensions tab, drag a ScriptManager control onto the page.
    2. The ScriptManager control must be placed in a form tag with runat=server.
    3. The ScriptManager control must be listed before any other controls in the forms that require it.
Adding a ScriptManager control to a page enables the ASP.NET AJAX JavaScript libraries at runtime. When a ScriptManager control is present on a page at runtime, at a minimum, three sections will be included on the page to initialize ASP.NET AJAX JavaScript: references to AJAX JavaScript, initialization of PageRequestManager, and initialization of the ASP.NET AJAX application components. These are described as follows:
    • ASP.NET AJAX includes a Hypertext Transfer Protocol (HTTP) handler (ScriptResourceHandler) to streamline the distribution of scripts to clients by compressing script content. Modifications to the web.config file to support ASP.NET AJAX expose the handler for use via the root path ScriptResource.axd. When a ScriptManager control is present on a page at runtime, a set of script tags similar to the following are included:
[JavaScript]
 < 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-4sbm1dKOIjJjgq4yMc1L5C0 & t = 633251404579172099 " type=" text / javascript "></script>
The standard ASP.NET WebResource handler includes a reference to the WebForms.js script callback library.
    • PageRequestManager works in conjunction with the ScriptManager control to register the controls that trigger asynchronous postbacks and the UpdatePanels that are updated. 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 on the page:
[JavaScript]
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 on the page at the bottom of the form in which the ScriptManager control resides:
[JavaScript]
Sys.Application.initialize();
The following table lists key members of the ScriptManager control:
ScriptManager members
Description
Properties
EnablePartialRendering
Enables partial rendering of a page, which enables you to update regions of the page individually by using the UpdatePanel control. By default, this property value is true.
Methods
RegisterAsyncPostBackControl
Registers a server control for asynchronous postbacks that can be used to update specific regions of the page. This method is used for controls outside 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.
  1. In the Visual Studio toolbar under the Extensions tab, add an UpdatePanel control by dragging an UpdatePanel control onto the page. Add the UpdatePanel control after the ScriptManager control.

    The following table lists key members of 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
There are two options: Always and Conditional. Always is the default and causes the UpdatePanel control to update upon every postback. Conditional causes the UpdatePanel control to update only when a trigger (registered or child control) initiates a postback.
  1. Add a Button and Label (both server controls) to the UpdatePanel control. Since the Button control implements IPostBackEventHandler and is within the UpdatePanel control, it initiates an asynchronous postback when clicked. Set the Text property on the Button control to Get Server Time. The page appears as follows:


  2. Handle the client event of the Button control as you would for a traditional postback. For example, add the declarative content of the page, add the OnClick attribute, and reference a method on the page, Button1_Click, as shown in the following code:
[JavaScript]
 < asp: Button id = Button1 onclick = Button1_Click Text = "Get Server Time" runat =
     "server" >  <  / asp: Button >
  1. In the event, set the Label1 Text property to the current time on the server as shown in the following code:
[JavaScript]
protected void Button1_Click(object sender, EventArgs e){
    Label1.Text = DateTime.Now.ToString();
}

Asynchronous postback events

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 of each step is provided.
  1. By default a server control button is rendered as a Hypertext Markup Language (HTML) input element that submits the form in which it resides. When a ScriptManager control is present on 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 PageRequestManager._onFormSubmit() private function.

    In this case, clicking the button submits the form and triggers an asynchronous postback since the button resides in an UpdatePanel control. Controls outside an UpdatePanel control need to register with the ScriptManager control to initiate an asynchronous postback. A new AJAX object, Sys.Web.WebRequest, is created, properties are set, and the Web request is invoked.
  2. When the Web request is invoked, it uses 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 control and the control that initiated the postback, a custom header (x-microsoftajax), the view state, and the event validation information.

    The following code shows an example request. Some of the general header information has been excluded:
[JavaScript]
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
  1. On the server, the ScriptManager control manages all page and control rendering via interaction with the ASP.NET AJAX System.Web.UI.PageRequestManager object and System.Web.UI.ScriptManager.IPage interface. PageRequestManager determines if the postback is asynchronous and initiated by a client using ASP.NET AJAX JavaScript. It searches for the x-microsoftajax header to contain the argument\value pair Delta=true. If true, the ScriptManager control intercepts all page content rendering and generates the HTTP response. If an UpdatePanel control 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, UpdatePanel controls, and triggers. The final section is optional and contains custom data items and script includes statements registered with the ScriptManager control during postback processing on the server.

    The following code shows an example response. Some of the general header information has been excluded:
[JavaScript]
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
  1. The partial postback response is returned to the browser client and processed by the Web request that wrapped the initial request. The body of the response is directed to the PageRequestManager._onFormSubmitCompleted() function by a handler registered via the WebRequest.add_completed function.

    The _onFormSubmitCompleted() function contains the logic to parse the body of the response. The logic updates page elements and view state, executes JavaScript includes statements, passes data items to their respective handlers, and modifies ASP.NET AJAX JavaScript components dynamically.


See Also:

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