Disabling Button on Asynchronous PostBack in C#


V4 Ajax Tutorials
Server Intellect Cloud Hosting

Disabling Button on Asynchronous PostBack in C#

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 precendence 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:

<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>

We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!

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:

<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime" runat="server" Text="Get Current Time" OnClick="btn_GetTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>

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:

using System.Threading;

..

protected void btn_GetTime_Click(object sender, EventArgs e)
{
Thread.Sleep(3000);
}

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

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:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);

function startRequest(sender, e) {
//disable button during the AJAX call
document.getElementById('<%=btn_GetTime.ClientID%>').disabled = true;
document.getElementById('<%=btn_GetTime.ClientID%>').value = 'Getting time..';
}
function endRequest(sender, e) {
//re-enable button once the AJAX call has completed
document.getElementById('<%=btn_GetTime.ClientID%>').disabled = false;
document.getElementById('<%=btn_GetTime.ClientID%>').value = 'Get Current Time';
}
</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.

<script type="text/javascript">
var instance = Sys.WebForms.PageRequestManager.getInstance();
instance.add_initializeRequest(instance_initializeRequest);

function instance_initializeRequest(sender, args) {
if (instance.get_isInAsyncPostBack()) {
alert('Still processing request. Please wait..');
args.set_cancel(true);
}
}
</script>

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

The ASPX will look something like this:

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="SM1" runat="server" />

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
<%= DateTime.Now.ToString() %>
<br />
<asp:Button ID="btn_GetTime" runat="server" Text="Get Current Time" OnClick="btn_GetTime_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
</form>
</body>
</html>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(startRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);

function startRequest(sender, e) {
//disable button during the AJAX call
document.getElementById('<%=btn_GetTime.ClientID%>').disabled = true;
document.getElementById('<%=btn_GetTime.ClientID%>').value = 'Getting time..';
}
function endRequest(sender, e) {
//re-enable button once the AJAX call has completed
document.getElementById('<%=btn_GetTime.ClientID%>').disabled = false;
document.getElementById('<%=btn_GetTime.ClientID%>').value = 'Get Current Time';
}
</script>

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
Oscar said:

Did anyone find a fix to the comment posted regarding the ValidationGroup property?

Posted Feb 4, 2010 9:12 AM
Luffe said:

Brilliant!!!

This is THE generic way of locking a web page during a postback.

My problem was finding a solution to the latency between 1st and 2nd postback in the new way of handling history in ASP.NET AJAX 3.5, and this solves it in a nice way.

Thanks for ending my 5+ hours searching the web for solutions to this one :)

Posted Jul 6, 2010 8:45 AM
Freelance SEO India said:

India’s leading Freelance SEO India services provider with main competency in Search Engine Optimization of websites.

Posted Dec 29, 2010 11:19 AM
Wooden tool boxes said:

In this tutorial, We Will Be Looking at how to use AJAX to make asynchronous calls, and how to manage aussi Those calls by disabling o Until The call button COMPLETE. Often, if a user Does not see near-immediate results When They make a request (click a button for example), Will Try to use That Make the call again. This CAN cause Problems, Especially When using AJAX have made The Last Call Will take over "any Successives That Are Currently in progress. A Good Way to Deal With This Is To Give the user visual feedback That IS Their request processing. This Can Be Done With An UpdateProgress control, for example. Purpose another way to do it Is To Disable the button whilst year Asynchronous request IS Being Processed. In this article, she look so amazing. She always prepare a performance maximally. That great!

Posted Feb 19, 2011 4:06 AM
Viagra livraison rapide said:

Asynchronous calls is great idea! Good code, thanks.

Posted Mar 9, 2011 5:28 PM
used car loans for bad credit said:

The layout for your web site is a bit off in OmniWeb. However I like your blog. I may have to install a normal browser just to enjoy it!

Posted Mar 9, 2011 5:29 PM
nk said:

hi if we use Response.End in Button click we are getting Script Processing Error.any idea.When i clicked Export to excel button i want to disable button after file generation i want to enable button

Posted Apr 18, 2011 7:02 AM
shrdev said:

Great Solution :). Thanks

Posted May 9, 2011 9:30 AM
1500 loan no credit check said:

I long looked for such code. Thanks.

Posted Jul 15, 2011 5:59 AM
www.outlet-louisvuitton.co.uk said:

www.outlet-louisvuitton.co.uk

Posted Aug 6, 2011 3:29 AM
Aleksandra Czajka said:

Check this out. I believe it is an easier way to disable any content on updatePanel asynchronous postback. http://thecodebug.com/?p=33. but, let me know.

Posted Aug 7, 2011 5:20 PM
Rui Machado said:

Aleksandra Czajka , the solution on your link , is without a dought the best if found so far.

simple , understandable, not to mutch code.....

Posted Sep 1, 2011 10:00 AM
helen olsson said:

Good work! I always like to leave comments whenever I see something unusual or impressive. I think we must appreciate those who do something especial. Keep it up, thanks

Helen Olsson.

Posted Oct 30, 2011 5:07 AM

Leave a Comment