Disabling Button on Asynchronous PostBack in C#


Server Intellect


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
Nice Tutorial said:
Posted May 7, 2009 12:43 PM
Internet gambling news report said:

I've just found that this won't work when controls have their ValidationGroup property set. The button will fire all validators regardless of whether they are in the same ValidationGroup or not. As yet I haven't found a fix. Anyone have any ideas?!Thanks

Posted Jun 27, 2009 2:37 AM
Please enter your name said:

Please enter a comment

Posted Nov 10, 2009 8:25 AM
cxzxzxz said:

xzxzxzcccccccccccccc

Posted Nov 21, 2009 2:00 AM
cxzxzxz said:

xzcxzccccccc

Posted Nov 21, 2009 2:01 AM
cxzxzxz said:

cxzzzzzzzzzzzzz

Posted Nov 21, 2009 2:01 AM
Oscar said:

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

Posted Feb 4, 2010 9:12 AM
free life insurance quotes said:

Im not sure why the VS.NET IDE does not let you initiate debugging when windows authentication is turned off; however, there is an easy workaround for this issue.Thanks

Posted Feb 24, 2010 9:47 AM
Bow Ties said:

Before the War,while black tie was still gaining acceptance, men would wear a white waistcoat, along with other details such as stiff fronted shirts,this was to create a more formal effect when for example ladies were present.The cummerbund,derived from military dress uniform in British India is worn with its pleats facing up and is normally of the same cloth as the bow tie and lapels.Maroon, the colour commonly worn to accompany black tie,may be used for the cummerbund in very informal or summer situations though note that this is not to match the bow tie which was always black.Single breasted styles should have no more than three buttons and double no more than three rows.

Posted Feb 26, 2010 2:21 PM
compare dental plans said:

A few dental clinics sign agreements with health coverage companies and agree     

Posted Feb 26, 2010 5:41 PM
compare dental plans said:

A few dental clinics sign agreements with health coverage companies and agree to accept or "take " the compensation presented by the insurance company

Posted Feb 26, 2010 5:42 PM
fibromyalgia said:

Practitioners contend that visceral osteopathy relieves imbalances and restrictions in the interconnections between the motion of all the organs and structures of the body—namely, nerves, blood vessels, and fascial compartments.

Posted Feb 27, 2010 7:52 PM
asope said:

There are lots of good <a rel="new tab" href="http://www.sexyjeans.org/">Women jeans</a> & <a rel="new tab" href="http://www.showerbase.org/">Shower base pan</a> for their attractive look and comfortable use.

Posted Mar 1, 2010 11:36 AM
best dental plans said:

Traditionally,an incision is made over the crest of the site where the implant is to be placed.This is referred to as a flap.

Posted Mar 8, 2010 11:01 AM
term life insurance quote said:

There are exceptions to this criterion. Lloyd's of London is famous for insuring the life or health of actors, actresses and sports figures.

Posted Mar 8, 2010 11:39 AM
online home insurance quote said:

Its nice to see this post where it can be used as a guide for the developers that i like to discuss about this in my blog thanks for sharing

Posted Mar 8, 2010 12:21 PM

Leave a Comment