Skip to content

Instantly share code, notes, and snippets.

@mattapayne
Created August 13, 2009 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattapayne/167335 to your computer and use it in GitHub Desktop.
Save mattapayne/167335 to your computer and use it in GitHub Desktop.
Shows how to disable a button on submit in ASP.NET while maintaining validation checks and form submission
public static class HtmlHelper
{
private const string DISABLED_BUTTON_CSS_CLASS = "disabled_button";
public static void SingleClick(Page page, Button btn)
{
string scriptKey = String.Format("click_once_button_{0}", btn.ValidationGroup);
if (!page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
{
StringBuilder sb = new StringBuilder();
sb.Append("function disableButtonOnClick(btn) ");
sb.Append("{");
sb.Append(" if(typeof(Page_ClientValidate) == 'function') ");
sb.Append("{");
sb.AppendFormat(" if(Page_ClientValidate('{0}') == false)", btn.ValidationGroup);
sb.Append(" {");
sb.Append(" return false;");
sb.Append(" }");
sb.Append(" btn.disabled = true;");
sb.Append(" btn.value = 'Working ...';");
sb.AppendFormat(" btn.setAttribute('className', '{0}');", DISABLED_BUTTON_CSS_CLASS);
sb.AppendFormat(" btn.setAttribute('class', '{0}');", DISABLED_BUTTON_CSS_CLASS);
sb.Append(" }");
sb.Append(" }");
page.ClientScript.RegisterClientScriptBlock(typeof(HtmlHelper), scriptKey, sb.ToString(), true);
btn.UseSubmitBehavior = false;
PostBackOptions options = new PostBackOptions(btn);
btn.OnClientClick = "disableButtonOnClick(this);" + page.ClientScript.GetPostBackEventReference(options) + ";return;";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment