mercoledì 13 giugno 2007

Preventing double postback

Today I had to make sure a certain button could not be pressed twice, to avoid processing errors. Initially I just set the disabled property to true, but that would not work since postback from disabled controls is inhibited. I invoked manually the postback, and it worked, but broke when validators prevented the postback. After a little bit of wondering, I crafted this small routine, to be placed in a Page-derived class for simplicity.

/// <summary>
/// Makes a certain button one-shot only,
/// preserving validator functionality
/// </summary>
/// <param name="btn">The button that can't be clicked twice</param>
protected void RegisterSinglePostButton(Button btn)
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
sb.Append("this.disabled = true;");
sb.Append(ClientScript.GetPostBackEventReference(btn, ""));
btn.Attributes.Add("onclick", sb.ToString());

It can be easily transformed in a control if needed, for further clarity.

Nessun commento: