Thursday, January 25, 2007

ClickOnce Button for ASP.Net 2.0

We have a couple of forms from which we get double submissions by people hitting the submit button again and again. We decided to go with a ClickOnce button that disables itself when the form submits. I saw a couple of solutions that implement it but nothing for ASP.Net 2.0.
I ended up implementing it in myself.

About 5 lines of code placed in the Page_Load event handler:


// Define the name and type of the client script on the page.
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
String cstext = "if (typeof(ValidatorOnSubmit) == 'function' && ValidatorOnSubmit() == false)return false; else { var myCtl = document.getElementById('" + this.SubmitButton.ClientID + "'); myCtl.value = 'Please wait...'; myCtl.disabled = true;}";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}

On the aspx page we have:

<asp:button id="SubmitButton" onclick="SubmitButton_Click" usesubmitbehavior="False" runat="server">


There are 2 gotchas here:
1. Make sure validation takes place and the page validates prior to disabling the button. This is done with JavaScript
2. Make sure the button is not rendered as input type submit otherwise when it is disabled it will not trigger the correct event handler on postback - for that we use: UseSubmitBehavior="False".

2 comments:

Shenhua GU said...

actually it works fine with UseSubmitBehavior="true"

Free eBooks said...

nice, it is working well. Thanks
free asp.net ebooks