Cancelling an Asynchronous PostBack in ASP.NET AJAX

Posted by: Suprotim Agarwal , on 7/19/2008, in Category ASP.NET AJAX
Views: 97982
Abstract: 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.
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.
 
If you liked the article,  Subscribe to my RSS Feed.
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Chaitanya on Sunday, July 20, 2008 1:13 PM
Thank you for explaining on how to cancel Async PostBack.
Comment posted by jim on Tuesday, July 22, 2008 7:49 PM
great article.
One question,
I have an updatepanel in master page, i have an updatepanel in a contentpage. both set to conditional for updatemode.
Now, the problem is that when I click the button inside the masterpage's updatepanel, the contentpage's updatepanel's datalist lost its data or unbind the datalist to be empty.
Is there something i did that i can make the masterpage's button click event inside the updatepanel without affecting the contentpage's updatepanel's datalist?
Comment posted by krishna on Wednesday, August 20, 2008 4:32 PM
Great Article, very helpful.
Comment posted by Calvin on Thursday, August 21, 2008 8:58 AM
This this implementation, in the abort functionality, when you do abort, and the rest of the server side function completes, does that change to the label go out to the client or does the server side function completes and then nothing happens (nothing is sent to the client browser)?

Thanks!  

P.S.  Good article.
Comment posted by raj on Wednesday, September 17, 2008 2:45 AM
in visual studio 2005 & framework 2.0 & Ajax version Version 1.0.20229 this article is not working
Comment posted by ccc on Tuesday, January 6, 2009 5:21 AM
hhddddddd
Comment posted by James King on Friday, March 27, 2009 12:06 PM
Great Article, It does help.. Much Appreciated

<a href="www.vouchercodes.net" target="_blank">Promotional Discount Voucher Codes</a>
Comment posted by Juma on Friday, March 27, 2009 12:08 PM
http://www.vouchercodes.net
Comment posted by Sai Krishna on Thursday, February 4, 2010 5:24 AM
It's a great article.....Any one can easily under stand the concept....I am very thankful for posting this type of articles.
Comment posted by If jezzy paying lebron im payin dwayne wade on Thursday, March 11, 2010 3:34 AM
Rating in this website sucks!
Comment posted by nozel on Saturday, March 13, 2010 6:28 AM
Really helpful,got the answer to my problem
Thanx.
Comment posted by Mehak Gupta on Tuesday, June 29, 2010 8:07 AM
its really very good knowledge for keen observers.........thanku so much n keep updating........... :-)
Comment posted by Bibhu on Monday, January 10, 2011 9:27 PM
Its a nice article
Comment posted by Toji on Monday, February 28, 2011 11:17 PM
I had a query which took sometime to execute.
When i hit the refresh button and in the midst if i want to stop the postback, this method will stop the progress as if it stopped the postback, but the query is running in the background, until the query execution is finished, until then i cannot do another postback on the page.
Comment posted by Simon on Friday, April 15, 2011 8:44 AM
Thanks for posting this article - Easy to follow, Well explained, and it works!
Comment posted by De on Tuesday, January 31, 2012 4:39 PM
Hi Suprotim,

  Your article has helped me on how to go about the issue I am having in my application. But still couldn't figure out what is causing it.

Below is my scenario:

->I have two user controls, ucA and ucB and a page mypage.aspx.
->ucA is being used in ucB and ucB is being displayed in mypage.aspx. Both user controls have update panels in them.
->I have two dropdown controls, drpl1 and drpl2 in ucB. And both dropdown list controls's autopostback property set to true. If I pick drpl1 then drpl2 gets update. When drpl2 gets picked there is another dropdown (autopostback=false) and that gets filled based on drpl2 selected value.

So by the time the mypage.aspx loads, based on the business rules either drpl1 or drpl2 gets focus and having focus is a must.

Now, say for instance, the drpl2 (most of the times drpl2 gets focus) gets focus when the page loaded. With out changing the option in the drpl2, if I click any where on the page then it does a postback. I would like to emphasis once again that I am not change option (i.e selectedIndexChanged shouldn't fire because I am not changing the option) in the drpl2 but it still does a postback.

So, to see what kind of post back it is doing I put this code in my page_load

If Page.IsPostBack Then
                If (ScriptManager.GetCurrent(Me.Page).IsInAsyncPostBack) Then
                    Dim s As String = "There is an Async post back"
                Else
                    Dim s1 As String = "There is no async post back"
                End If


            End If

and when i debugged I figured that it is doing an IsInAsyncPostBack.

So upon searching, came across your article and trying to cancel the AsncPostBack that was taking place above.

Here is how I am doing it:

in mypage.aspx I put this javascript code

  function pageLoad() {
            var manager = Sys.WebForms.PageRequestManager.getInstance();

            if (manager.get_isInAsyncPostBack()) {
                alert('This is in Asyncpostback');
                //manager.add_beginRequest(cancelPostBack);
                manager.add_initializeRequest(cancelPostBack);
            }

            function cancelPostBack(sender, args) {
                alert('Cancelling auto post back')
                args.set_cancel(true);
            }
        }

and loaded the mypage.aspx and tried to remove the focus by clicking any where on the page or any get focus to any other text box and tried to type in some text in it and I lost the typed text because of the page refresh.

When the page loads for the first time, from the above javascript it always fired the alert('This is in Asyncpostback'); never fired the alert('Cancelling auto post back'); box!
(Note: It fired the alert('This is in Asyncpostback'); box after executing my page_load code. That means it for some reason doesn't go to the cancelPostBack event at all)

But after the first trail, and in all the subsequent trails of loosing focus and changing the options in the drpl2 it always fired the alert('Cancelling auto post back'); box and it cancelled the postback.

Now my issue is I do not want any kind of post back happen when the mypage.aspx loads for the first time and when the drpl2 lost its focus. And by theory it shouldn't postback because I am not changing the option in the drpl2 am I just removing the foucs.

I made a small test in another webpage with a dropdown (with autopost=true and also with OnSelectedIndexChanged="somethingchanged") and it doesn't postback just because it lost the focus. It only does when I change the option.

Hope the explanation is understandable. Do you think I am missing some thing here and what might be causing to post the page back when the drpl2 lost its focus when the page loads for the first time.

Thank you in advance for taking time to read my issue.

Dev
Comment posted by Sandeep Singh on Monday, April 7, 2014 2:10 AM
Plz cancel my asp net I can't pay this money again thanks

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel