[ASP.NET AJAX] Client Page Request Lifecycle with UpdatePanel Control

In my previous article, I explained the client page lifecycle in terms of the “Sys.Application” object and how to handle the events of the object. (Please read this).

ASP.NET AAJAX provides another way to interact with the client-side page events when you use the “UpdatePanel” control. The “Sys.WebForms.PageRequestManager” object provides a mechanism to respond to the client-side page lifecycle events.  

1.  Sys.WebForms.PageRequestManager Class

The “PageRequestManager” object manages partial-page updates of the “UpdatePanel” control by using client scripts.

You are not creating the instance of the “PageRequestManager” class directly. When the condition is met, the object is created for you and you can access it through the “getInstance()” method.

– Conditions –

  • the page contains at least one UpdatePanel control
  • the ScriptManager control’s “SupportsPartialRendering” value is true
var prm = Sys.WebForms.PageRequestManager.getInstance();

2. Partial Page Update Lifecycle Events

The “PageRequestManager” object becomes available when partial rendering is enabled and goes through a series of events.

  • initializeRequest: raised before processing of the asynchronous request starts. (used to cancel a postback)
  • beginRequest: raised before processing of an asynchronous postback starts and the postback is sent to the server. (used to set request headers or to begin an animation that indicates that the page is processing)
  • pageLoading: raised after the response from the server to an asynchronous postback is received but before any content on the page is updated. (used to provide a custom transition effect for updated content)
  • pageLoaded: raised after all content on the page is refreshed. (used to provide a custom transition effect for updated content)
  • endRequest: raised after an asynchronous postback is finished and control has been returned to the browser. (used to provide a notification to users or to stop the progress animation)

3. Event Handlers

You can use the “add_<EventName>” or “remove_<EventName>” methods of the “PageRequestManager” class to add or remove event handlers.

  • The event handlers have 2 parameters: sender, args
  • To access the property values for client API properties, you must call property accessor methods that are named with the get_ and set_ prefixes.

4. EventArgs Classes

– Properties of “Sys.WebForms.InitializeRequestEventArgs” –

  • postBackElement: gets the postback element that initiated the asynchronous postback
  • request: gets the request object that represents the current postback
  • updatePanelsToUpdate: gets or sets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client.
  • cancel: inherited from the “Sys.CancelEventArgs“, used to cancel the caused event

– Properties of “Sys.WebForms.BeginRequestEventArgs” –

  • postBackElement: gets the postback element that initiated the asynchronous postback
  • request: gets the request object that represents the current postback
  • updatePanelsToUpdate: gets or sets a list of UniqueID values for UpdatePanel controls that should re-render their content, as requested by the client.

– Properties of “Sys.WebForms.PageLoadingEventArgs” –

  • dataItems: gets a JSON data structure that contains data items that were registered by using the RegisterDataItem method of the ScriptManager class
  • panelsDeleting: gets an array of HTML <div> elements that represent UpdatePanel controls that will be deleted from the DOM
  • panelsUpdating: gets an array of HTML <div> elements that represent UpdatePanel controls that will be updated in the DOM

– Properties of “Sys.WebForms.PageLoadedEventArgs” –

  • dataItems: gets a JSON data structure that contains data items
  • panelsCreated: gets an array of HTML <div> elements that represent UpdatePanel controls that were created when the DOM was updated during the last asynchronous postback
  • panelsUpdated: gets an array of HTML <div> elements that represent UpdatePanel controls that were updated when the DOM was updated during the last asynchronous postback

– Properties of “Sys.WebForms.EndRequestEventArgs” –

  • dataItems: gets a JSON data structure that contains data items
  • error: gets the Error object
  • errorHandled: gets or sets a value that indicates whether the error has been handled
  • response: gets a response object that is represented by the “WebRequestExecutor” class

5.  Checking AsyncPostback

The “isInAsyncPostBack” property indicates whether the “PageRequestManager” object is processing a postback. When the request is initiated and this value is alredy true, it means that the previous request has not been completed yet.

function InitRequestHandler(sender, args) {
  var prm = Sys.WebForms.PageRequestManager.getInstance();
  if (prm.get_isInAsyncPostBack()) {
    // 'Still working on previous request.';
    args.set_cancel(true);
  } else {
    // 'let's request';
  }
}

[Note] In server side, you can use the “IsInAsyncPostBack” property of a “ScriptManager” object to check whether the current postback is asynchronous or not.

6. Canceling a Request

The “initializeRequest” event is the place to check whether it is OK to request an asynchronous postback. When the “isInAsyncPostBack” property is true (a postback is alreay in progress) in the “initializeRequest” event handler, you have 2 chioces:

  • Canceling the previous request:  Use the “abortPostBack()” method of the “PageRequestManager” object
  • Canceling the current request: Set the “cancel” property of the “InitializeRequestEventArgs” object passed as an “arg” object to the handler

7. Error Handling

The “EndRequestEventArgs” include the “error” property to allow you to check erorr that have occurred during an asynchronous request.

After handlinging the error, you need to set the “errorHandled” property of the “EndRequestEventArgs” object to “true” to indicated you have handled the error.

function EndRequestHandler(sender, args) {
  if (args.get_error() != null) {
    // handle the error
    args.set_errorHandled(true);
  }
}

Also the “response” property of the “EndRequestEventArgs” object has the “aborted” property to check whether the request is aborted.

function EndRequestHandler(sender, args) {
  if (args.get_response().get_aborted()) {
    // aborted.
  }
}

8. Testing Event Handlers

// ClientLifeCycle.js
var loadingCount = 0;

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitRequestHandler);
prm.add_beginRequest(BeginRequestHandler);
prm.add_pageLoading(pageLoadingHandler);
prm.add_pageLoaded(pageLoadedHandler);
prm.add_endRequest(EndRequestHandler);

function InitRequestHandler(sender, args) {
  if (prm.get_isInAsyncPostBack() && args.get_postBackElement().id == 'cancelRequest') {
    $get('messageArea').innerHTML = 'Previous/Current Requests canceled.';
    prm.abortPostBack();
    args.set_cancel(true);
  }
  else if (prm.get_isInAsyncPostBack() && args.get_postBackElement().id == 'requestTime') {
    $get('messageArea').innerHTML = 'Still working on previous request.';
    args.set_cancel(true);
  }
  else if (!prm.get_isInAsyncPostBack() && args.get_postBackElement().id == 'requestTime') {
    $get('messageArea').innerHTML = 'Processing....';
  }
}

function BeginRequestHandler(sender, args) {
  var elem = args.get_postBackElement();
  $get('messageArea').innerHTML = elem.value + ' processing...';
}

function pageLoadingHandler(sender, args) {
  loadingCount += 1;
  $get('messageArea').innerHTML = ' loading (' + loadingCount + ') ...';
}

function pageLoadedHandler(sender, args) {
  $get('messageArea').innerHTML = 'The panel is loaded...';
}

function EndRequestHandler(sender, args) {
  if (args.get_error() != null) {
    var errorName = args.get_error().name;
    if (errorName.length > 0) {
      args.set_errorHandled(true);
      $get('messageArea').innerHTML = 'The panel did not update successfully.';
    }
  } else {
    if (args.get_response().get_aborted())
      $get('messageArea').innerHTML = 'The update is aborted.';
    else
      $get('messageArea').innerHTML = 'The panel has been updated successfully.';
  }
}
<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Scripts>
    <asp:ScriptReference Path="~/Chapters/AjaxTest/ClientLifeCycle.js" ScriptMode="Release" />
  </Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
  Current Time: <asp:Label ID="nowText" runat="server"></asp:Label>
  <br /><br />
  <asp:Button ID="requestTime" runat="server" Text="Request the current Time"
    onclick="requestTime_Click" />
  <asp:Button ID="cancelRequest" runat="server" Text="Cancel the Request" />
  <br /><br />
  <div id="messageArea"></div>
  </ContentTemplate>
</asp:UpdatePanel>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s