In this tutorial, we will be looking at how to use AJAX to make Asynchronous calls, and also how to manage those calls by disabling our button until the call completes. Often, if a user doesn’t see near-immediate results when they make a request (click a button for example), that user will try to make the call again.

This can cause problems, especially when using AJAX as the last call made will take precedence over any that are currently in progress. A good way to deal with this is to give the user visual feedback that their request is processing.

This can be done with an UpdateProgress control, for example. But another way to do it is to disable the button whilst an Asynchronous request is being processed.

To demonstrate how to do this, we will create a small form with an UpdatePanel and a Button. The button will get the current time on the server, which will take only milliseconds to complete – too fast for us to demonstrate the button being disabled. For this example, we will slow the request down by making it sleep for 2 seconds before processing.

We start by building out our ASPX page. Let’s add a ScriptManager and an UpdatePanel:

In our UpdatePanel, we are going to output the current Date and Time, and also include a Button to allow the user to update it:

Notice we have a handler for the Button’s click event. This is where we are going to slow the process down. In the code-behind, we will add the following:

All that is left to do is to disable the button during the Async PostBack. We will do this using JavaScript, as it will be executed in the browser and will be effective immediately. At the bottom of the page, we add the following script:

Here, we are calling a function on the start of an Async Request, and then another method on the end of the Request. These functions change the disabled value of the button, and also the text. Now when we run this application, we will be able to click the button to retrieve the current date and time, and display it to the page. We are also pausing the request for two seconds, so that we can see during the request that the button is disabled and the text is temporarily changed. When the request is complete, however, we re-enable the button and change the text back.

The ASPX will look something like this:

Thank you for reading our tutorial on AJAX Controls, we aim to provide the best AJAX tutorials. Learning AJAX in ASP.NET is easy and we hope you are getting your hands dirty by trying different things and coming up with your own ideas. If you have any questions or concerns, please feel free to suggest a tutorial or you can comment below in the comments section.

Download Source Files