In this tutorial, you will learn how to cancel an Asynchronous PostBack that is currently in progress. This is useful when a user has submitted a request to a web page that uses AJAX, and they can see that their request is pending – through the use of an UpdateProgress, for example – and they decide they want to cancel that request for whatever reason. We can make this a reality for users with a little JavaScript.

For this example, we will create one main UpdatePanel and then a nested UpdatePanel and an UpdateProgress. We should have something like this:

Now we will place a Literal in the second UpdatePanel, and also a Button:

Notice here that we add a handler to the Button Click event. We will also set the Date and Time on Page_Load, but only the first time it loads – not on PostBacks. The code-behind will look something like this:

On load and on button click we are simply displaying the current date and time in the Literal control. Also on the button click, we are putting it to sleep first, for 3 seconds, which will give us a chance to cancel the process before it’s complete.

Now all that is left to do is to add the JavaScript to handle the cancellation of the Async PostBack. It is important to note that this method will not actually stop the Server from processing the request; it will only cause the Page Request Manager to ignore the response from the Server. With this in mind, if the Server is performing a lengthy process, it may be worth making a new Async call to explicitly halt that activity.

Add the following script to the bottom of the page. This will check to see if the Cancel button is the one making the call, and if so, will abort the pending PostBack.

Download Source Files