Click here to Skip to main content
Licence CPOL
First Posted 13 Apr 2004
Views 211,922
Downloads 2,428
Bookmarked 97 times

ClickOnce Button Server Control

By Eric Plowe | 13 Apr 2004
An article that shows how to do what everyone said you shouldn't or couldn't do with the ASP.NET button control.
3 votes, 5.7%
1

2
3 votes, 5.7%
3
6 votes, 11.3%
4
41 votes, 77.4%
5
4.72/5 - 53 votes
3 removed
μ 4.51, σa 1.80 [?]

Introduction

Back in the days of classic ASP, when we wanted to prevent the end user from repeatedly mashing the submit button, we would disable the button with JavaScript. But with ASP.NET, it's not as simple as that anymore. When you disable any form element client side, you essentially disable it server side as well since its name value pair will not be sent with the form post. The drawback from this is that the button_click event is now rendered useless. It will never be raised!

I have searched the ASP.NET forums over for an elegant solution for this problem and I have seen a couple of nice work arounds but nothing that gives the true effect of rendering the button disabled after being clicked. So I came up with my own. Enter the ClickOnceButton server control.

The server control behaves exactly like the intrinsic button control with the exception of two new properties: DisableAfterClick and DisabledText.

When DisableAfterClick is true, the button will be disabled client side after click. If DisabledText is set, the text of the button will be set to the DisabledText after the button is disabled. Useful if you want to get a li'l visual cue (such as changing the buttons text to 'Processing..').

The main work happens in the AddAttributesToRender event:

    Protected Overrides Sub AddAttributesToRender(ByVal writer As HtmlTextWriter)
        Dim strOnClick As String

        If IsNothing(MyBase.Page) Then
            MyBase.Page.VerifyRenderingInServerForm(Me)
        End If

        writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit")
        writer.AddAttribute(HtmlTextWriterAttribute.Name, MyBase.UniqueID)
        writer.AddAttribute(HtmlTextWriterAttribute.Value, Me.Text)

        If Not IsNothing(MyBase.Page) And Me.CausesValidation_
                    And MyBase.Page.Validators.Count > 0 Then
            If Me.DisableAfterClick Then
                strOnClick = Me.GetClickOnceClientValidateEvent()
            Else
                strOnClick = Me.GetClientValidateEvent()
            End If

            If MyBase.Attributes.Count > 0 And Not _
                    IsNothing(MyBase.Attributes("onclick")) Then
              strOnClick = String.Concat(MyBase.Attributes("onclick"), strOnClick)
              MyBase.Attributes.Remove("onclick")
            End If

            writer.AddAttribute("language", "javascript")
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, strOnClick)
        ElseIf DisableAfterClick = True Then
            strOnClick = Me.GetOnceClickJavascript()

            If MyBase.Attributes.Count > 0 And Not _
                   IsNothing(MyBase.Attributes("onclick")) Then
              strOnClick = String.Concat(MyBase.Attributes("onclick"), strOnClick)
              MyBase.Attributes.Remove("onclick")
            End If

            writer.AddAttribute("language", "javascript")
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, strOnClick)
        End If

        MyBase.AddAttributesToRender(writer)
    End Sub

This creates the button programmatically as well as determines if the button causes validation and there are validators on the page or if the button just simply needs to be disabled. You'll notice it calls three distinct different properties. These are what makes the magic happen. They are as follows:

    Friend ReadOnly Property GetClientValidateEvent() As String
        Get
            Return "if (typeof(Page_ClientValidate) _
                      == 'function') Page_ClientValidate(); "
        End Get
    End Property

    Friend ReadOnly Property GetClickOnceClientValidateEvent() As String
        Get
            Return "if (typeof(Page_ClientValidate) == 'function') _
                    { if(Page_ClientValidate()) { " + _
                    GetOnceClickJavascript + " }} else { " + _
                    GetOnceClickJavascript + " }"
        End Get
    End Property

    Friend ReadOnly Property GetOnceClickJavascript() As String
        Get
            Return "document.getElementsByName('" + _
              Me.OnceClickBtnName + "').item(0).setAttribute('name'," + _
              "this.getAttribute('name')); this.disabled = true; " + _
              IIf(DisabledText = String.Empty, String.Empty, _
              "this.value = '" + DisabledText + "';") + _
              "this.form.submit();"
        End Get
    End Property

The property, GetClientValidateEvent(), returns the same JavaScript that the framework normally appends if your button control causes validation and there are validators on the page. This is to handle the scenario where you have the button on a page, set to not be disabled after click, and you have validators.

The property, GetClickOnceClientValidateEvent(), returns a slightly modified version of the above script. This handles the scenario when there are validators on the page and you want the button to be disabled after click. But you want to make sure it only gets disabled if the Page_ClientValidate() returns true or in the case of non IE browsers it'll just disable the button and submit.

The property, GetOnceClickJavascript(), returns the base set of JavaScript that disables handles disabling the button. It also makes sure the button gets sent over in the post so that the button click will be raised. It does this by exchanging the name attribute of a hidden field with the name of the button. The framework just needs to see the name/ID of the control sent over to raise its click event. The hidden field gets registered in the control's OnInit(EventArgs) event.

    Protected Overrides Sub OnInit(ByVal e As EventArgs)
        If Me.DisableAfterClick And Not Me.IsHiddenFieldRegistered Then
            MyBase.Page.RegisterHiddenField(Me.OnceClickBtnName, "")
        End If

        MyBase.OnInit(e)
    End Sub

    Private Function IsHiddenFieldRegistered() As Boolean
        For Each ctl As Control In MyBase.Page.Controls
            If TypeOf ctl Is HtmlControls.HtmlInputHidden Then
                If ctl.ID = Me.OnceClickBtnName Then
                    Return True
                End If
            End If
        Next

        Return False
    End Function

The default constant value of OnceClickBtnValue is __onceClickBtn. The IsHiddenFieldRegistered function just makes sure that the field is registered only once. This allows us to possibly have more than one button on the form that disables after click.

You may be wondering why I didn't just inherit from the System.Web.UI.WebControls.Button class. Well, the reason was the AddAttributesToRender event. I could have just hijacked that event and added the same code I have here and not have had to go through the entire process of creating the properties, functions, etc. The problem was I still needed to call MyBase.AddAttributesToRender which would then finally call the AddAttributesToRender in the System.Web.UI.WebControls.WebControl class. If I inherited from the Button class, I would end up with two onclicks and no control over the JavaScript outputted in the event of validation. This gives me complete control.

To use this in your own projects, simply add the clickoncebutton assembly to your toolbox and drag and drop it onto your webform and you're set! Enjoy!

Note: Tested on IE 6.0 and NS 7.0 with version 1.1 of the .NET framework.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Eric Plowe

Software Developer (Senior)

United States United States

Member
28 year old developer currently working for Sapient, Inc.
 
Specialities include (but not limited to): C# And VB.Net, VB6 & 5, VBScript(Classic asp), JavaScript guru, web services, xml/xsl, C++ (Win32/COM/DCOM)
 
In my spare time I try to continue my pursuit of music (when i have time!).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionenabling/ disabiling button PinmemberMember 28350560:18 5 Nov '08  
GeneralThanks Pinmemberhido26280:22 27 Aug '08  
GeneralThanks a lot works for aspnet1.1 Pinmemberyeya8a6:53 25 Jun '08  
GeneralCommandButton ClickOnceButton Server Control PinmemberS.S.Sivaprasad21:47 16 Jan '08  
GeneralThis button saved my *SS Pinmemberrobtathome@charter.net8:24 24 Apr '07  
GeneralRe: This button saved my *SS PinmemberEric Plowe6:03 3 Aug '07  
NewsA solution for asp.net 2.0 Pinmembersimplicityc13:24 26 Jan '07  
Questiondoesnt seem to trigger the ajax UpdateProgress control Pinmemberpdenomme5:52 4 Jan '07  
Questionsupport ValidationGroup functionality? Pinmemberlimkek16:42 17 Dec '06  
GeneralToo much trouble PinmemberRobotovich13:16 25 Oct '06  
GeneralClient scripts on .NET 2.0 Pinmemberjportelas6:48 3 Oct '06  
NewsOne more click once button article PinmemberTittle Joseph0:43 7 Aug '06  
GeneralJust what I needed PinmemberNathan Wheeler5:03 28 Mar '06  
GeneralRe: Just what I needed PinmemberEric Plowe6:09 28 Mar '06  
GeneralPrompt ClickOnce Button Server Control Pinmemberqherb9:52 13 Mar '06  
I have developed a new server control - PromptClickOnce button based on ClickOnce button. Besides the features of validation and ClickOnce, it integrates a new feature: prompt a confirmation dialog box. When it is clicked, it first validates the page, then popup a dialog to ask user's confirmation before performing ClickOnce. If you need this button, simply add it to ClickOnceButton project, and build new ClickOnceButton assemly. After you add the new assemly to your .NET toolbox, you will see this new server control. Have fun to play with it!
 
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Drawing
 

<ToolboxBitmap(GetType(System.Web.UI.WebControls.Button)), DefaultEvent("Click")> _
Public Class PromptClickOnceButton
Inherits System.Web.UI.WebControls.WebControl
Implements IPostBackEventHandler
 
Public Event Click As EventHandler
Public Event Command As System.Web.UI.WebControls.CommandEventHandler
 
Private Const OnceClickBtnName As String = "__onceClickBtn"
 

<Browsable(True), Category("Behavior")> _
Public Property DisableAfterClick() As Boolean
Get
Dim o As Object = MyBase.ViewState("DisableAfterClick")
Return IIf(IsNothing(o), False, CBool(o))
End Get
Set(ByVal Value As Boolean)
MyBase.ViewState("DisableAfterClick") = Value
End Set
End Property
 
<Browsable(True), Category("Behavior")> _
Public Property CommandName() As String
Get
Dim o As Object = MyBase.ViewState("CommandName")
Return IIf(IsNothing(o), String.Empty, CStr(o))
End Get
Set(ByVal Value As String)
MyBase.ViewState("CommandName") = Value
End Set
End Property
 
<Browsable(True), Category("Behavior")> _
Public Property CommandArgument() As String
Get
Dim o As Object = MyBase.ViewState("CommandArgument")
Return IIf(IsNothing(o), String.Empty, CStr(o))
End Get
Set(ByVal Value As String)
MyBase.ViewState("CommandArgument") = Value
End Set
End Property
 
<Browsable(True), Category("Appearance")> _
Public Property DisabledText() As String
Get
Dim o As Object = MyBase.ViewState("DisabledText")
Return IIf(IsNothing(o), String.Empty, CStr(o))
End Get
Set(ByVal Value As String)
MyBase.ViewState("DisabledText") = Value
End Set
End Property
 
<Browsable(True), Category("Appearance")> _
Public Property Text() As String
Get
Dim o As Object = MyBase.ViewState("Text")
Return IIf(IsNothing(o), "Button", CStr(o))
End Get
Set(ByVal Value As String)
MyBase.ViewState("Text") = Value
End Set
End Property
 
<Browsable(True), Category("Behavior")> _
Public Property CausesValidation() As Boolean
Get
Dim o As Object = MyBase.ViewState("CausesValidation")
Return IIf(IsNothing(o), True, CBool(o))
End Get
Set(ByVal Value As Boolean)
MyBase.ViewState("CausesValidation") = Value
End Set
End Property
 
<Browsable(True), Category("Behavior")> _
Public Property ConfirmBeforeSubmit() As Boolean
Get
Dim o As Object = MyBase.ViewState("ConfirmBeforeSubmit")
Return IIf(IsNothing(o), True, CBool(o))
End Get
Set(ByVal Value As Boolean)
MyBase.ViewState("ConfirmBeforeSubmit") = Value
End Set
End Property
 
<Browsable(True), Category("Appearance")> _
Public Property ConfirmationMessage() As String
Get
Dim o As Object = MyBase.ViewState("ConfirmationMessage")
Return IIf(IsNothing(o), String.Empty, CStr(o))
End Get
Set(ByVal Value As String)
MyBase.ViewState("ConfirmationMessage") = Value
End Set
End Property
 
Public Sub New()
MyBase.New(HtmlTextWriterTag.Input)
End Sub
 

<Browsable(False)> _
Friend ReadOnly Property GetClientValidate() As String
Get
Return "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); "
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetClickOnceClientValidate() As String
Get
Return "if (typeof(Page_ClientValidate) == 'function') { if(Page_ClientValidate()) { " + _
GetClickOnceJavascript + " }} else { " + _
GetClickOnceJavascript + " }"
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetClickOnceJavascript() As String
Get
Return "document.getElementsByName('" + Me.OnceClickBtnName + "').item(0).setAttribute('name'," + _
"this.getAttribute('name')); this.disabled = true; " + _
IIf(DisabledText = String.Empty, String.Empty, "this.value = '" + DisabledText + "';") + _
"this.form.submit();"
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirmJavascript() As String
Get
Return "return confirm('" + EscapedMessage(ConfirmationMessage) + "');"
 
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirm() As String
Get
 
Return "confirm('" + EscapedMessage(ConfirmationMessage) + "')"
 
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirmReturn() As String
Get
 
Return "if (confirm('" + EscapedMessage(ConfirmationMessage) + "')) " + _
"{ return true;} else {return false;} "
 
End Get
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirmClientValidate() As String
Get
Return "if (typeof(Page_ClientValidate) == 'function') { if(Page_ClientValidate()) { " + _
GetConfirmReturn + " }} else { " + _
GetConfirmReturn + " }"
End Get
 
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirmClickOnce() As String
Get
Return " if( " + GetConfirm + ") { " + _
GetClickOnceJavascript + " } else {return false;}"
End Get
 
End Property
 
<Browsable(False)> _
Friend ReadOnly Property GetConfirmClickOnceClientValidate() As String
Get
Return "if (typeof(Page_ClientValidate) == 'function') { if(Page_ClientValidate()) { " + _
GetConfirmClickOnce + " }} else { " + _
GetConfirmClickOnce + " }"
End Get
End Property
 
Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
End Sub
 
Protected Overrides Sub AddAttributesToRender(ByVal writer As HtmlTextWriter)
Dim strOnClick As String
 
If IsNothing(MyBase.Page) Then
MyBase.Page.VerifyRenderingInServerForm(Me)
End If
 
writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit")
writer.AddAttribute(HtmlTextWriterAttribute.Name, MyBase.UniqueID)
writer.AddAttribute(HtmlTextWriterAttribute.Value, Me.Text)
 
If Not IsNothing(MyBase.Page) And Me.CausesValidation And MyBase.Page.Validators.Count > 0 Then
If Me.DisableAfterClick Then
If Me.ConfirmBeforeSubmit Then
strOnClick = Me.GetConfirmClickOnceClientValidate
Else
strOnClick = Me.GetClickOnceClientValidate
End If
Else
If Me.ConfirmBeforeSubmit Then
strOnClick = Me.GetConfirmClientValidate
Else
strOnClick = Me.GetClientValidate
End If
End If
If MyBase.Attributes.Count > 0 And Not IsNothing(MyBase.Attributes("onclick")) Then
strOnClick = String.Concat(MyBase.Attributes("onclick"), strOnClick)
MyBase.Attributes.Remove("onclick")
End If
 
writer.AddAttribute("language", "javascript")
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, strOnClick)
 
ElseIf Me.DisableAfterClick Or Me.ConfirmBeforeSubmit Then
If Me.DisableAfterClick Then
If Me.ConfirmBeforeSubmit Then
strOnClick = Me.GetConfirmClickOnce
Else
strOnClick = Me.GetClickOnceJavascript
End If
Else
If Me.ConfirmBeforeSubmit Then
strOnClick = Me.GetConfirmJavascript
End If
End If
 
If MyBase.Attributes.Count > 0 And Not IsNothing(MyBase.Attributes("onclick")) Then
strOnClick = String.Concat(MyBase.Attributes("onclick"), strOnClick)
MyBase.Attributes.Remove("onclick")
End If
 
writer.AddAttribute("language", "javascript")
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, strOnClick)
End If
 
MyBase.AddAttributesToRender(writer)
 
End Sub
 
Protected Overrides Sub OnInit(ByVal e As EventArgs)
If Me.DisableAfterClick And Not Me.IsHiddenFieldRegistered Then
MyBase.Page.RegisterHiddenField(Me.OnceClickBtnName, "")
End If
MyBase.OnInit(e)
End Sub
 
Private Function IsHiddenFieldRegistered() As Boolean
For Each ctl As Control In MyBase.Page.Controls
If TypeOf ctl Is HtmlControls.HtmlInputHidden Then
If ctl.ID = Me.OnceClickBtnName Then
Return True
End If
End If
Next
Return False
End Function
 
Protected Overridable Sub OnClick(ByVal e As EventArgs)
RaiseEvent Click(Me, e)
End Sub
 
Protected Overridable Sub OnCommand(ByVal e As System.Web.UI.WebControls.CommandEventArgs)
RaiseEvent Command(Me, e)
End Sub
 
Private Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
If Me.CausesValidation Then
MyBase.Page.Validate()
End If
Me.OnClick(New EventArgs)
Me.OnCommand(New System.Web.UI.WebControls.CommandEventArgs(Me.CommandName, Me.CommandArgument))
End Sub
 
Private Function EscapedMessage(ByVal strMsg As String) As String
Return Replace(ConfirmationMessage, "'", "\'")
End Function
 
End Class

 
-- modified at 10:49 Tuesday 2nd May, 2006
GeneralRe: Prompt ClickOnce Button Server Control PinmemberAnjum Rizwi20:32 1 May '06  
GeneralRe: Prompt ClickOnce Button Server Control Pinmemberqherb5:39 2 May '06  
GeneralRe: Prompt ClickOnce Button Server Control PinmemberAnjum Rizwi20:47 2 May '06  
Generalthank you Pinmemberearthdance8:42 30 Nov '05  
GeneralClick and Disable PinmemberYao Xi23:39 25 Oct '05  
Generalsubmit and onsubmit PinmemberKirk Quinbar7:18 19 Sep '05  
GeneralMy C# version - with some limitations Pinsusstrondborg14:59 18 Aug '05  
GeneralRe: My C# version - with some limitations Pinsusstrondbor19:24 18 Aug '05  
GeneralRe: My C# version - with some limitations Pinmembertrondborg7:28 19 Aug '05  
GeneralRe: My C# version - with some limitations Pinmemberhydernaqvi12:45 27 Feb '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120210.1 | Last Updated 14 Apr 2004
Article Copyright 2004 by Eric Plowe
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid