
Introduction
There often comes the time when you want to prevent your users from hitting a submit button on your page twice (or whatever times they think is appropriate). As we all know there unfortunately is no "built-in" functionality to archive this behavior.
Background
The idea is basically quite simple. When somebody clicks a button (we will use an <asp:button />
for the following example), a client side JavaScript function is called which disables the button and submits the page. After the page gets submitted (Page.IsPostBack = True
), the server side method assigned to the button should fire and persist the user's input. Unfortunately it�s not that easy. If the button is disabled before the page gets submitted, the server side method assigned to the button does not fire. This is because the �Name/Value pair� of the button is not incorporated in the �Form Collection� of the page if the button is disabled. The trick is to disable the button after the page gets submitted and here is how it�s done.
Using the code
This is how the code in the .aspx page looks like. To allow you to simply copy & paste the code, I included everything within <HTML />
.
<HTML>
<HEAD>
<title>One Time Clickable Button</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
<script language="javascript">
<!--
function DisableButton() {
document.forms[0].submit();
window.setTimeout("disableButton('" +
window.event.srcElement.id + "')", 0);
}
function disableButton(buttonID) {
document.getElementById(buttonID).disabled=true;
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:Button ID="btnSave" Text="Save" Runat="server"></asp:Button>
</form>
</body>
</HTML>
The same applies to the code-behind file. The purpose of System.Threading.Thread.Sleep(5000)
is simply to emulate a long running save operation, calculation, etc.
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
btnSave.Attributes.Add("onclick", "DisableButton()")
End Sub
Private Sub btnSave_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnSave.Click
System.Threading.Thread.Sleep(5000)
Response.Write("Page has been saved.")
End Sub
Have fun!