Creating a One-Click Button in ASP.NET (C#)

Category: .NET Programming Tags:
February 24, 2010

Many times you place a button on a form which calls an external process, such as a SQL Query or some other action that may take some time. After not long, the user gets bored with waiting and presses the button again – and again, triggering umpteen requests which make the delay even longer. This may be followed by closing the browser and complaining to whoever is local.

There’s an easy way to give the user a happier experience, simply by preventing them pressing the button again and giving some comforting feedback that something is happening and all is well. It’s a bit of a con trick really, as the browser don’t know for certain if all is really going to plan.

There’s several ways to do this, but the basic idea here is to use JavaScript to disable the button as soon as it is pressed. However, remember we still need to trigger the ASP.NET click event. I also like to put a label on the page which says ‘Updating’ or whatever, maybe even an animated image, just to pacify the user.

In this example, the user presses the ‘Save’ button (named ‘cmdSave’). I’ll add attributes to it which will automatically create a JavaScript function to disable the button when clicked, set the label to ‘PROCESSING’ and then call the click event. It’s simple code. Don’t forget to re-enable the button once the save has finished if you need to.

On the ASPX Page:

<asp:Button ID=”cmdSave” runat=”server” OnClick=”cmdSave_Click” Text=”Save” />
<asp:Label ID=”lblProgress” runat=”server”></asp:Label>

In the Code Behind:

public void Page_Load( object sender, EventArgs e ) {

if ( !Page.IsPostBack ) {

cmdSave.Attributes.Add( “onclick”,
+ ClientScript.GetPostBackEventReference( cmdSave, “” ).ToString() );


// After you save, don’t forget to re-enable the button

protected void cmdSave_Click( object sender, EventArgs e ) {
cmdSave.Enabled = true;
lblProgress.Text = “”;

Sometimes you may have to disable more than one button, as the user may still get bored and start pressing menu items and hyperlinks. You can use the same technique to disable more than one component or maybe disable a <div>. In the past I’ve used the ASP.NET AJAX controls of UpdatePanel and UpdateProgress with a little CSS to cover the entire browser with a sort of modal box forcing the user to wait.

You can’t stop the user closing the browser or powering off their PC but a little feedback actually does wonders for their sanity and your reputation.