I was wondering what to write about, and I realized that I needed to post something about what we have trouble to find the solution. Then I decided to write how to disable a button in a HTML page (using Asp.Net and C#) after the user clicked it. Avoiding so that the user click several times and send several requests to the server.
The solution uses basically javascript to disable the button just after the user clicked it. The method we used lays in a different namespace, called Common, which we pass the button and the text we wish to appear after the user click it (something like “Wait”), as parameters.
The method is bellow:
public static void DisableOnClick(System.Web.UI.WebControls.Button btn, string Message) { string theScript = ""; if ( btn.CausesValidation ) { theScript = @" if (typeof(Page_ClientValidate) == 'function') { if (Page_ClientValidate() == false ) return false; }"; } theScript += @" this.value = '" + Message + @"'; this.disabled = true; document.getElementById('" + btn.ClientID + @"') .disabled = true;" + btn.Page.ClientScript.GetPostBackEventReference(btn, string.Empty) + @";"; btn.Attributes["onclick"] = theScript; }
Basicaly what the method does is to create a script and attach it at the button click event. This script verify if the button does any kind of validation and, if any, run that code, after it the button is disabled and the new text is setted to the button, then the postback call is made.
Bellow is an example of use:
private void Page_Load(object sender, System.EventArgs e) { Common.DisableOnClick(btnRegister, "Wait..."); }
Simple, easy and usefull…
Enjoy