Вы находитесь на странице: 1из 17

Cancelling an Asynchronous PostBack in ASP.NET AJAX http://www.dotnetcurry.com/ShowArticle.aspx?

ID=176

Cancelling an Asynchronous PostBack in ASP.NET Ajax


The behavior of an Asynchronous postback is quiet similar to a synchronous postback. In an asynchronous model, all the server side events occur, as they do in a synchronous model. The Microsoft AJAX Library also raises client side events. However when the page is rendered, asynchronous postback renders only the contents of the update panel, where as in a synchronous postback, the entire page is recreated and sent back to the browser. In one of the previous articles, I had shown how to cancel a Synchronous Postback using ASP.NET. In this article, we will see how to cancel an Asynchronous postback. I assume you have some basic experience developing ASP.NET Ajax applications and have installed the ASP.NET Ajax Library and ASP.NET Control Toolkit. As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008). I have tested the sample using Version 3.0.20229 (targeting .NET Framework 3.5 and Visual Studio 2008); although I believe it will run with Version 1.0.20229 too. The Application(Sys.Application) and PageRequestManager(Sys.WebForms.PageRequestManager) classes in the AJAX Library are prominent in raising events during the client life cycle of an ASP.NET AJAX Web page. If you have an update panel on your page, you can manipulate asynchronous postbacks by handling events exposed by the PageRequestManager class. We will shortly see how we can use the client events of the PageRequestManager class to provide functionality like cancelling a postback or aborting the current postback etc. The process starts by subscribing to the initializeRequest event of the PageRequestManager class which gets raised during the initialization of the async postback. The event gives you an ideal place to cancel the currently executing asynchronous postback by using the isInAsyncPostBack property of the PageRequestManager class, to check whether an asynchronous postback is currently in progress. If it is, and the user performs another postback, you have the ability to cancel the new postback. Note: ASP.NET Ajax can perform only one Asynchronous postback at a time. Let us see this in action: Step 1: Open Visual Studio > File > New Web Site > ASP.NET Web Site > Choose the location and language and click OK. Step 2: Drag and drop a ScriptManager and an UpdatePanel to the page. In the update panel, drag and drop three buttons and a label control. The first button will cause the first postback, followed by the second one which will cause the second postback and the final button to abort the current postback. After registering the events, the code will look similar to the following: <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:Button runat="server" Text="PostBackFirst" ID="btnPostF" onclick="btnPostF_Click"/> <asp:Button runat="server" Text="PostBackSecond" ID="btnPostS" onclick="btnPostS_Click"/> <asp:Button runat="server" Text="AbortPostBack" ID="btnAbort"/>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </form> </body> In the event handlers, add the following code: C# protected void btnPostF_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(4000); Label1.Text = "PostBack 1 Completed"; } protected void btnPostS_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(4000); Label1.Text = "PostBack 2 Completed"; } VB.NET Protected Sub btnPostF_Click(ByVal sender As Object, ByVal e As EventArgs) System.Threading.Thread.Sleep(4000) Label1.Text = "PostBack 1 Completed" End Sub Protected Sub btnPostS_Click(ByVal sender As Object, ByVal e As EventArgs) System.Threading.Thread.Sleep(4000) Label1.Text = "PostBack 2 Completed" End Sub Here, we are introducing a delay of 4 seconds when a button click occurs. You can replace this with your processing code, like retrieving results from a database or a similar operation. Step 3: To the <head> element on the page, add the following javascript code: <script type="text/javascript"> function pageLoad() { Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(cancelPostBack); } function cancelPostBack(sender, args) { if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) { alert('One postback at a time please'); args.set_cancel(true); } } </script> As already explained in the introduction of this article, the code above demonstrates how to use and register the initializeRequest event to determine whether an asynchronous postback is currently

executing by using the isInAsyncPostBack property. You can also cancel the current request by using the cancel property of the Sys.CancelEventArgs class. Note: You can get the ID of the element which has initiated a new postback by postBackElement property of the Sys.WebForms.InitializeRequestEventArgs class. Something similar to: var ctrl = args.get_postBackElement() which returns the postback element that initiated the asynchronous postback. Step 4: The last step left is to build functionality to abort the current postback by using the abortPostBack() of the PageRequestManager class. To do so, add the following code to the onClientClick() of the btnAbort as shown below: <asp:Button runat="server" Text="AbortPostBack" ID="btnAbort" OnClientClick="Sys.WebForms.PageRequestManager.getInstance().abortPostBack(); alert('Postback Cancelled');"/> The entire source will look similar to the following: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Cancel Async PostBack</title> <script type="text/javascript"> function pageLoad() { Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(cancelPostBack); } function cancelPostBack(sender, args) { if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) { alert('One postback at a time please'); args.set_cancel(true); } } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <asp:Button runat="server" Text="PostBackFirst" ID="btnPostF" onclick="btnPostF_Click"/> <asp:Button runat="server" Text="PostBackSecond" ID="btnPostS" onclick="btnPostS_Click"/> <asp:Button runat="server" Text="AbortPostBack" ID="btnAbort" OnClientClick="Sys.WebForms.PageRequestManager.getInstance().abortPostBack(); alert('Postback Cancelled');"/>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>

In order to test the functionality, follow these steps: 1. Run the application. 2. Click on PostBackFirst. Now immediately click on PostBackSecond. You will receive a message One postback at a time please. So our script has successfully discovered that there is an async postback currently in progress and hence does not allow the other. 3. Now to check how to abort a current async postback, click on either the PostBackFirst or on PostBackSecond and wait for 4 seconds. The default behavior is that when the current thread wakes up (remember we did Thread.Sleep()), a message is displayed PostBack Completed. Now click on the button again and this time, click on the AbortPostBack button. You will see that the postback has aborted and the PostBack Completed message is never displayed. Now this was just a simple (call it lousy), but useful demonstration of how to cancel and abort async postbacks. I am sure you will be able to find out better implementations of this functionality in your applications. I would love to hear back from you if you implement in a practical scenario. I hope you liked the article and I thank you for viewing it.

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX
You cannot call server-side code directly from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions. One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more integrated with our solution. The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript. Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh. I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end. Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok. Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ContactName in the other two textboxes. The textboxes that will display ContactName has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following: <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"/> <div> <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label> <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br /> <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None" ReadOnly="True"></asp:TextBox><br /> <br /> <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label> &nbsp; <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br /> <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None" ReadOnly="True"></asp:TextBox>&nbsp;<br /> </div> </form>

Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ASP.NET AJAX enabled website. The tag </configSections> along with some other tags automatically get added to the web.config. <connectionStrings> <removename="all"/> <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/> </connectionStrings> Step 3: Currently we will add a method, GetContactName() which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod. C# public static string GetContactName(string custid) { if (custid == null || custid.Length == 0) return String.Empty; SqlConnection conn = null; try { string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; conn = new SqlConnection(connection); string sql = "Select ContactName from Customers where CustomerId = @CustID"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("CustID", custid); conn.Open(); string contNm = Convert.ToString(cmd.ExecuteScalar()); return contNm; } catch (SqlException ex) { return "error"; } finally { conn.Close(); } } VB.NET Public Shared Function GetContactName(ByVal custid As String) As String If custid Is Nothing OrElse custid.Length = 0 Then Return String.Empty End If Dim conn As SqlConnection = Nothing Try Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString conn = New SqlConnection(connection) Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID" Dim cmd As SqlCommand = New SqlCommand(sql, conn) cmd.Parameters.AddWithValue("CustID", custid) conn.Open() Dim contNm As String = Convert.ToString(cmd.ExecuteScalar()) Return contNm Catch ex As SqlException

Return "error" Finally conn.Close() End Try End Function Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method: C# [System.Web.Services.WebMethod] public static string GetContactName(string custid) { } VB.NET <System.Web.Services.WebMethod()> _ Public Shared Function GetContactName(ByVal custid As String) As String End Function At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/> Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file. function CallMe(src,dest) { var ctrl = document.getElementById(src); // call server side method PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest); } // set the destination textbox value with the ContactName function CallSuccess(res, destCtrl) { var dest = document.getElementById(destCtrl); dest.value = res; } // alert message on some failure function CallFailed(res, destCtrl) { alert(res.get_message()); }

Step 6: We now need to reference this JavaScript file from our aspx page and invoke the CallMe() method whenever the textbox loses focus. To do so: Add a reference to the javascript file in the body tag as shown below: <body> <script type="text/javascript" language="javascript" src="script.js"> </script> <form id="form1" runat="server">

Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event C# if (!Page.IsPostBack) { txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')"); txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')"); } VB.NET If (Not Page.IsPostBack) Then txtId1.Attributes.Add("onblur", txtId1.ClientID & "', '" & txtContact1.ClientID & txtId2.Attributes.Add("onblur", txtId2.ClientID & "', '" & txtContact2.ClientID & End If "javascript:CallMe('" & "')") "javascript:CallMe('" & "')")

As shown above, we are using the Attributes.Add that lets us add an attribute to the server controls System.Web.UI.AttributeCollection object. The function CallMe kept in the script.js file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ContactName will be retrieved in the destination textbox. Well that is all that is needed to invoke server side code from client side. Run the code. Type ALFKI in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ContactName returned is displayed in the second textbox below the first one, in our case the value displayed is Maria Anders.

Troubleshooting: PageMethods Is 'Undefined' error


1. Try setting EnablePageMethods="true" in the script manager tag <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/> 2. Don't add the javascript references or code in the <head /> section. Add it to the <body> tag. <body> <script type="text/javascript" language="javascript" src="script.js"> </script> <form id="form1" runat="server"> </form> </body>

3. Page methods needs to be static in code behind.


using using using using using using System; System.Linq; System.Runtime.Serialization; System.ServiceModel; System.ServiceModel.Activation; System.ServiceModel.Web;

[ServiceContract(Namespace = "TM")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class GreetingService { // Add [WebGet] attribute to use HTTP GET [OperationContract] public void DoWork() { // Add your operation implementation here return; } // Add more operations here and mark them with [OperationContract] [OperationContract] public string GreetUser(string uname) { return "Hello " + uname; } } <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Create AJAX-enabled WCF Service</title> <script language="javascript" type="text/javascript"> function btnCallWCF_onclick() { var greeto = new TM.GreetingService(); greeto.GreetUser($get("txtUNm").value, OnGreetingComplete, OnError); } function OnGreetingComplete(result) { $get("dispGreeting").innerHTML = result; } function OnError(result) { alert(result.get_message()); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/GreetingService.svc" /> </Services> </asp:ScriptManager> <input id="btnCallWCF" type="button" value="Greet User" onclick="return btnCallWCF_onclick()" /> <input id="txtUNm" type="text" /> <div id="dispGreeting"> </div> </div> </form> </body> </html>

Ajax Client Life-Cycle Events


A WebForms based page that uses Microsoft Ajax raises the same server life-cycle events as an ASP.NET 4 Web page and in addition raises client life-cycle events. The client events enable you to customize the UI for both postbacks and for asynchronous postbacks (partial-page updates). The client events also help you manage custom script components during the lifetime of the page in the browser. The client events are raised by classes in the Microsoft Ajax Library. These classes are automatically instantiated when a page contains Microsoft Ajax server controls. The client classes provide APIs that enable you to bind to events and to provide handlers for those events. Because the Microsoft Ajax Library is browser independent, the code you write for your handlers works the same in all supported browsers. he two main Microsoft Ajax Library classes that raise events during the client life cycle of a WebForms based page are the Application and PageRequestManager classes. The Application class is instantiated in the browser when the page contains a ScriptManager control. The Application class resembles the Page server control, which derives from the Control class, but provides additional functionality for raising server events. Similarly, the Application class derives from the Sys.Component class, but raises client life-cycle events that you can handle. If a page contains a ScriptManager control and one or more UpdatePanel controls, the page can perform partial-page updates (if partial-page rendering is enabled and supported in the browser). In that case, an instance of the PageRequestManager class is automatically available in the browser. The PageRequestManager class raises client events that are specific to asynchronous postbacks. For details about partial-page rendering Event Order for Common Scenarios

The order of events depends on what controls are used on the page and what type of request is made (initial request, postback, or asynchronous postback). This section describes the order of events for several common scenarios.
Initial Request

During the initial request for the page, a limited number of client events are raised. Assume the following scenario for the initial request:
y y y

The page contains a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering property are both true. The request is a GET request. A response from the server is returned successfully.

The following client events occur, in this order: 1. 2. 3. 4. The initial request is sent to the server. The response is received by the client. The Application instance raises the init event. The Application instance raises the load event.

The init event of the Application instance is raised only one time for the life of the page in the browser. It is not raised for subsequent asynchronous postbacks. During an initial request, no PageRequestManager events are raised.
Asynchronous Postback

An asynchronous postback sends some page data to the server, receives a response, and updates a part of the page. Assume the following scenario for an asynchronous postback:
y y y y

The page contains a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering properties are both true. The page contains an UpdatePanel control, and the control's ChildrenAsTriggers property is true. A button inside the UpdatePanel control initiates an asynchronous postback. A response from the server is returned successfully.

The following client events occur, in this order: 1. 2. 3. 4. 5. 6. 7. 8. 9. The button inside the UpdatePanel is clicked, which initiates an asynchronous postback. The PageRequestManager instance raises the initializeRequest event. The PageRequestManager instance raises the beginRequest event. The request is sent to the server. The response is received by the client. The PageRequestManager instance raises the pageLoading event. The PageRequestManager instance raises the pageLoaded event. The Application instance raises the load event. The PageRequestManager instance raises the endRequest event.

For more information, see Working with Partial-Page Rendering Events. Note that the load event of the Application instance is raised after the PageRequestManager pageLoaded event and before its endRequest event.
Multiple Asynchronous Postbacks

Multiple asynchronous postbacks can occur when users initiate a new request before a previously initiated request has finished processing on the server or in the browser. Assume the following scenario for multiple asynchronous postbacks:
y y y y

The page contains a ScriptManager control and the control's SupportsPartialRendering and EnablePartialRendering property are both true. The page contains an UpdatePanel control. A button inside the UpdatePanel control that initiates an asynchronous postback is clicked two times. The second click occurs while the server is processing the request initiated by the first click. A response to the first request is returned successfully from the server.

The following client events occur, in this order: 1. 2. 3. 4. A button inside the UpdatePanel is clicked, which initiates an asynchronous postback. The PageRequestManager instance raises the initializeRequest event. The PageRequestManager instance raises the beginRequest event. The request is sent to the server.

5. The button is clicked again, which initiates a second asynchronous postback. 6. The PageRequestManager instance raises the initializeRequest event for the second button click. 7. The PageRequestManager instance raises the endRequest event for the first button click. 8. The PageRequestManager instance raises the beginRequest event for the second button click. 9. The request initiated by the second click is sent to the server. 10. The response is received for the second click. 11. The PageRequestManager instance raises the pageLoading event. 12. The PageRequestManager instance raises the pageLoaded event. 13. The Application instance raises the load event. 14. The PageRequestManager instance raises the endRequest event. The default behavior of asynchronous postbacks is that the most recent asynchronous postback takes precedence. If two asynchronous postbacks occur in sequence, and if the first postback is still being processed in the browser, the first postback is canceled. If the first postback has been sent to the server, the server processes the second request when it arrives and does not return the first request. For information about how to give precedence to a specific asynchronous postback, see Giving Precedence to a Specific Asynchronous Postback.
Browsing Away from a Page

When the user browses away from a page, the current page is unloaded from the browser and you can handle the unload event to free resources. Assume the following scenario for browsing away from a page:
y y

The page contains a ScriptManager control and the control's SupportsPartialRendering and EnablePartialRendering property are both true. The target page exists.

The following client events are raised, in this order: 1. 2. 3. 4. The request for new page is initiated. The response for the new page is received by the browser. The Application instance raises the unload event. The new page is displayed.

If there is an error in the request for the new page, the unload event is still raised, but the new page is not displayed.

Working with Partial-Page Rendering Events


.NET Framework 4

2182

The PageRequestManager class in the Microsoft Ajax Library coordinates with the ScriptManager and UpdatePanel server controls on an AJAX-enabled ASP.NET Web page to enable partial-page updating. The PageRequestManager class exposes methods, properties, and events to make client programming easier when page elements are performing asynchronous postbacks. For example, the PageRequestManager class enables you to handle events in the client page life cycle and to provide custom event handlers that are specific to partial-page updates. To use the PageRequestManager class in client script, you must put a ScriptManager server control on the Web page. The EnablePartialRendering property of the ScriptManager control must be set to true (which is the default). When EnablePartialRendering is set to true, the client-script library that contains the PageRequestManager class is available in the page.
Getting an Instance of the PageRequestManager Class

There is one PageRequestManager instance per page. You do not create an instance of the class. Instead, you get a reference to the current instance by calling the getInstance method, as shown in the following example:
C# VB
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);

When you have the current instance of the PageRequestManager class, you can access all its methods, properties, and events. For example, you can get the isInAsyncPostBack property to determine whether an asynchronous postback is in progress, as shown in the following example:
C# VB
function InitializeRequest(sender, args) { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelPostBack') { prm.abortPostBack(); } }

If the EnablePartialRendering property of the ScriptManager control is false, you cannot access the isInAsyncPostBack property because there is no PageRequestManager instance.
Client Page Life-cycle Events

During ordinary page processing in the browser, the window.onload DOM event is raised when the page first loads. Similarly, the window.onunload DOM event is raised when the page is refreshed or when the user moves away from the page. However, these events are not raised during asynchronous postbacks. To help you manage these types of events for asynchronous postbacks, the PageRequestManager class exposes a set of events. These resemble window.load and other DOM events, but they also occur during asynchronous postbacks. For each asynchronous postback, all page events in the PageRequestManager class are raised and any attached event handlers are called.
Note

For synchronous postbacks, only the pageLoaded event is raised. You can write client script to handle events raised by the PageRequestManager class. Different event argument objects are passed to handlers for different events. The following table summarizes the PageRequestManager class events and the corresponding event argument classes. The order of the events in the table is the order of the events for a single asynchronous postback without errors.
initializeRequest

Raised before the request is initialized for an asynchronous postback. Event data is passed to handlers as an InitializeRequestEventArgs object. The object makes available the element that caused the postback and the underlying request object.
beginRequest

Raised just before the asynchronous postback is sent to the server. Event data is passed to handlers as a BeginRequestEventArgs object. The object makes available the element that caused the postback and the underlying request object.
pageLoading

Raised after the response to the most recent asynchronous postback has been received but before any updates to the page have been made. Event data is passed to handlers as a PageLoadingEventArgs object. The object makes available information about what panels will be deleted and updated as a result of the most recent asynchronous postback.
pageLoaded

Raised after page regions are updated after the most recent postback. Event data is passed to handlers as a PageLoadedEventArgs object. The object makes available information about what panels were created or updated. For synchronous postbacks, panels can only be created, but for asynchronous postbacks, panels can be both created and updated.
endRequest

Raised when request processing is finished. Event data is passed to handlers as an EndRequestEventArgs object. The object makes available information about errors that have occurred and whether the error was handled. It also makes available the response object.

If you use the RegisterDataItem method of the ScriptManager control to send extra data during an asynchronous postback, you can access that data from the PageLoadingEventArgs, PageLoadedEventArgs, and EndRequestEventArgs objects. The sequence of events varies with different scenarios. The order in the previous table is for a single, successful asynchronous postback. Other scenarios include the following:
y y y y

Multiple postbacks where the most recent postback takes precedence, which is the default behavior. Only events for the most recent asynchronous postback are raised. Multiple postbacks where one postback is given precedence, which cancels all subsequent postbacks until it is finished. Only the initializeRequest event is raised for canceled postbacks. An asynchronous postback that is stopped. Depending on when the postback is stopped, some events might not be raised. An initial request (HTTP GET) of a page, or a page refresh. When a page is first loaded or when it is refreshed in the browser, only the pageLoaded event is raised.

Stopping and Canceling Asynchronous Postbacks

Two common tasks are to stop an asynchronous postback that is underway and to cancel a new request before it has begun. To perform these tasks, you do the following:
y y

To stop an existing asynchronous postback, you call the abortPostback method of the PageRequestManager class. To cancel a new asynchronous postback, you handle the initializeRequest event of the PageRequestManager class and set the cancel property to true.

Stopping an Asynchronous PostBack

The following example shows how to stop an asynchronous postback. The initializeRequest event handler script checks whether the user has chosen to stop the postback. If so, the code calls the abortPostback method.
<%@ Page Language="C#" %> <%@ Import Namespace="System.Collections.Generic" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void NewsClick_Handler(object sender, EventArgs e) { System.Threading.Thread.Sleep(2000); HeadlineList.DataSource = GetHeadlines(); HeadlineList.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { HeadlineList.DataSource = GetHeadlines(); HeadlineList.DataBind(); } } // Helper method to simulate news headline fetch.

private SortedList GetHeadlines() { SortedList headlines = new SortedList(); headlines.Add(1, "This is headline 1."); headlines.Add(2, "This is headline 2."); headlines.Add(3, "This is headline 3."); headlines.Add(4, "This is headline 4."); headlines.Add(5, "This is headline 5."); headlines.Add(6, "(Last updated on " + DateTime.Now.ToString() + ")"); return headlines; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Canceling Postback Example</title> <style type="text/css"> body { font-family: Tahoma; } #UpdatePanel1{ width: 400px; height: 200px; border: solid 1px gray; } div.AlertStyle { font-size: smaller; background-color: #FFC080; width: 400px; height: 20px; visibility: hidden; } </style> </head> <body> <form id="form1" runat="server"> <div > <asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="CancelPostback.js" /> </Scripts> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="Server" > <ContentTemplate> <asp:DataList ID="HeadlineList" runat="server"> <HeaderTemplate> <strong>Headlines</strong> </HeaderTemplate> <ItemTemplate> <%# Eval("Value") %> </ItemTemplate> <FooterTemplate> </FooterTemplate> <FooterStyle HorizontalAlign="right" /> </asp:DataList> <p style="text-align:right"> <asp:Button ID="RefreshButton" Text="Refresh" runat="server" OnClick="NewsClick_Handler" /> </p> <div id="AlertDiv" class="AlertStyle"> <span id="AlertMessage"></span>

&nbsp;&nbsp;&nbsp;&nbsp; <asp:LinkButton ID="CancelRefresh" runat="server"> Cancel</asp:LinkButton> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>

Canceling New Asynchronous Postbacks

The following example shows how to give precedence to a specific asynchronous postback. This cancels all subsequent asynchronous postbacks until the current one finishes. (By default, the most recent asynchronous postback takes precedence.) The initializeRequest event handler checks whether the asynchronous postback was initiated by an element on the page that has precedence. If it was, all subsequent postbacks are canceled by setting the cancel property of the InitializeRequestEventArgs object. The InitializeRequestEventArgs event inherits from the CancelEventArgs class, where the cancel property is defined.

Вам также может понравиться