如果多次点击,请禁用"提交"按钮..(C#)

Muk*_*mar 4 c# asp.net button

我的问题是,我有一个简单的Web表单,其中包含两个文本框和一个按钮.页面上有一些asp.net验证器控件.所以我希望客户端在完成所有验证后禁用按钮.并且在禁用按钮后也是如此,我正在执行一些服务器端代码.所有这一切工作正常,但是,如果我设置按钮的回发网址,它会失败.bellow是编码的一部分,可以给你一些简短的想法.任何提示都将受到高度赞赏.......

我想在复合控件中实现此功能.这是按钮类

public class MyButton : Button
{

    protected override void OnPreRender(EventArgs e)
    {
        if (this.CausesValidation)
        {
            if (!String.IsNullOrEmpty(this.ValidationGroup))
            {
                this.Attributes.Add("onclick", @"javascript:

             if (typeof(Page_ClientValidate) == 'function')
                 {
                    if (Page_ClientValidate('" + this.ValidationGroup + "')){" + this.ClientID + ".disabled=true;" + Page.GetPostBackEventReference(this) +

              "}else{return;}}  else{" + this.ClientID + ".disabled=true;" + Page.GetPostBackEventReference(this) + "}");
            }

            else
            {
                this.Attributes.Add("onclick", @"javascript:

                 if (typeof(Page_ClientValidate) == 'function')
                   {
                      if (Page_ClientValidate()){" + this.ClientID + ".disabled=true;" + Page.GetPostBackEventReference(this) +
                  "}else{return;}}  else{" + this.ClientID + ".disabled=true;" + Page.GetPostBackEventReference(this) + "}");
            }
        }
        else
            this.Attributes.Add("onclick", "javascript:" + this.ClientID + ".disabled=true;" + Page.GetPostBackEventReference(this));

        base.OnPreRender(e);
    }
Run Code Online (Sandbox Code Playgroud)

Geo*_*kos 11

这是执行此操作的正确且简单的方法:

在您的应用程序中创建一个帮助器方法(比如在Utlity命名空间中):

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

现在,您可以通过每个网页的代码调用:

    Utility.PreventMultipleClicks(button1)
Run Code Online (Sandbox Code Playgroud)

其中button1是您要阻止多次点击的按钮.

这样做只是将点击处理程序设置为:this.disabled = true

然后附加按钮自己的回发处理程序,所以我们得到:

onclick="this.disabled=true";__doPostBack('ID$ID','');"
Run Code Online (Sandbox Code Playgroud)

这不会破坏页面的默认行为,并且可以按预期在所有浏览器中使用.

请享用!