Why doesn't my form post when I disable the submit button to prevent double clicking?

后端 未结 10 1333
广开言路
广开言路 2020-12-31 19:06

Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to han

10条回答
  •  渐次进展
    2020-12-31 19:53

    This is the correct and simple way to do this:

    It works in all browsers (unlike the accepted solution above).

    Create a helper method in your application (say in a Utlity Namespace):

        Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
            button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
        End Sub
    

    Now from the code behind of each of your web pages you can simply call:

        Utility.PreventMultipleClicks(button1, page)
    

    where button1 is the the button you want to prevent multiple clicks.

    What this does is simply sets the on click handler to: this.disabled=true

    and then appends the buttons own post back handler, so we get:

    onclick="this.disabled=true";__doPostBack('ID$ID','');"

    This does not break the default behaviour of the page and works in all browsers as expected.

    Enjoy!

提交回复
热议问题