• Grey out Submit button after click - ASP.NET

    by Venkata Koppaka | Jul 02, 2010

    This post is small snippet I had to come up with to grey out the submit button after clicking it so the user doesn't click it twice.

    I am using a post in asp.net forums http://forums.asp.net/p/1057086/1868122.aspx as reference.

    The version I am writing here is tailored down version of what the forums website discusses.

    Here is the C# Utility method that generates a script.

    1         ///  <summary> 
    2         /// Generates auto-disable butotn 
    3         /// </summary> 
    4         /// <param name="p">Page Instance</param> 
    5         /// <param name="btn">Button Instance</param> 
    6         /// <param name="disabledText">Text to display on button when clicked</param> 
    7         /// <returns></returns> 
    8         public static string GetLockButtonJscript(Page p, Button btn, string disabledText) 
    9         { 
    10             disabledText = disabledText == "" ? "Processing..." : disabledText; disabledText = disabledText.Replace("'", ""); 
    11  
    12             StringBuilder sb = new StringBuilder(); 
    13             if (btn.CausesValidation && p.Validators.Count > 0 && btn != null) 
    14             { 
    15                 sb.Append("if (typeof(Page_ClientValidate) == 'function') { "); sb.Append("if (Page_ClientValidate('" + btn.ValidationGroup + "') == false) { return false; }} "); 
    16  
    17             } 
    18              
    19             PostBackOptions opt = new PostBackOptions(btn, "", "", false, true, true, true, true, btn.ValidationGroup); 
    20  
    21             sb.Append(p.ClientScript.GetPostBackEventReference(opt)); 
    22             sb.Append(";"); 
    23  
    24             sb.Append("this.disabled='true';this.value='" + disabledText + "';"); 
    25              
    26             return sb.ToString(); 
    27         } 

    To use this method in a .aspx file and disable a button just include this line of code in the Page_Load event -

    1        protected void Page_Load(object sender, EventArgs e) 
    2         { 
    3             btnSubmit.Attributes.Add("onclick", GetLockButtonJscript(this.Page, btnSubmit, "Processing...")); 
    4         } 

    Hope this Helps,

     

    Cheers,

    Venkata


    Go comment!