C# ASP.Net双击问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1498269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:09:23  来源:igfitidea点击:

ASP.Net double-click problem

c#asp.netjavascriptonclickdouble-click

提问by David Archer

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)

我的 ASP.net 页面有一个小问题。如果用户双击“提交”按钮,它将写入数据库两次(即对图像按钮执行两次“onclick”方法)

How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?

我怎样才能做到这一点,如果用户点击图像按钮,只有图像按钮被禁用?

I've tried:

我试过了:

<asp:ImageButton 
     runat="server" 
     ID="VerifyStepContinue" 
     ImageUrl=image src 
     ToolTip="Go" 
     TabIndex="98" 
     CausesValidation="true" 
     OnClick="methodName" 
     OnClientClick="this.disabled = true;" />

But this OnClientClick property completely stops the page from being submitted! Any help?

但是这个 OnClientClick 属性完全阻止了页面被提交!有什么帮助吗?

Sorry, yes, I do have Validation controls... hence the icky problem.

抱歉,是的,我确实有验证控件......因此是棘手的问题。



Working on this still, up to this point now:

到目前为止,仍然在做这件事:

ASP code:

ASP代码:

 <asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
 ...
 <asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />

C# code:

C#代码:

         private Random
    random = new Random();


    protected void Page_Load(object sender, EventArgs e)
    {
        //Use a Token to make sure it has only been clicked once.
        if (Page.IsPostBack)
        {
            if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
            {
                InputMethod();
            }
            else
            {
                // double click
            }
        }

        double next = random.Next();

        hidToken.Text = next + "";
        Session["NextToken"] = next;

Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.

实际上......这几乎有效。双击问题几乎已解决(是的!)但图像仍未隐藏。

采纳答案by Noon Silk

The general approach is twofold.

一般的方法是双重的。

Serverside:

服务器端

  1. On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
  2. On submit, check that the hidden form field equals the session variable (beforesetting it again)
  3. Do work
  1. 在页面加载时,生成一个令牌(使用System.Random),将其保存在会话中,并将其写入隐藏的表单字段
  2. 在提交时,检查隐藏的表单字段是否等于会话变量(再次设置之前
  3. 做工作

Clientside:

客户端

Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.

与您拥有的类似,但可能只是隐藏按钮,并将其替换为诸如“提交”之类的文本。

The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).

客户端需要注意的重要一点是,用户可以通过点击“转义”来取消帖子,因此您应该考虑在这里做什么(取决于它们的距离,令牌不会被使用,所以你'需要将按钮从禁用/隐藏状态恢复)。

Complete example follows:

完整示例如下:

C# (includes code to see it in action):

C#(包括代码以查看它的实际效果):

<html>
<head runat="server">
    <title>double-click test</title>
    <script language="c#" runat="server">
    private Random
        random = new Random();

    private static int
        TEST = 0;

    public void Page_Load (object sender, EventArgs ea)
    {
        SetToken();
    }

    private void btnTest_Click (object sender, EventArgs ea)
    {
        if( IsTokenValid() ){
            DoWork();
        } else {
            // double click
            ltlResult.Text = "double click!";
        }
    }

    private bool IsTokenValid ()
    {
        bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
        SetToken();
        return result;
    }

    private void SetToken ()
    {
        double next = random.Next();

        hidToken.Value       = next + "";
        Session["NextToken"] = next;
    }


    private void DoWork ()
    {
        TEST++;
        ltlResult.Text = "DoWork(): " + TEST + ".";
    }
    </script>
</head>
<body>
    <script language="javascript">
        var last = null;
        function f (obj)
        {
            obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
            // Note: Disabling it here produced strange results. More investigation required.
            last = obj;
            setTimeout("reset()", 1 * 1000);
            return true;
        }

        function reset ()
        {
            last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
            last.disabled = "false";
        }
    </script>
    <form id="form1" runat="server">
        <asp:HiddenField runat="server" ID="hidToken" />
        <asp:ImageButton runat="server" ID="btnTest"
            OnClientClick="return f(this);"
            ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
        <pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
    </form>
</body>
</html>

回答by David Basarab

I have solved this by setting a hidden field on the client click before hitting the server.

我已经通过在点击服务器之前在客户端单击上设置一个隐藏字段来解决这个问题。

Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.

然后在服务器中我检查隐藏字段,如果该值是例如“FALSE”,这可能意味着我可以或不能执行该操作。

回答by jrummell

If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:

如果您在页面上进行了验证,则禁用按钮客户端会有点棘手。如果验证失败,您不想禁用该按钮。这是添加客户端事件处理程序的片段:

private void BuildClickOnceButton(WebControl ctl)

{

System.Text.StringBuilder sbValid = new System.Text.StringBuilder();

sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");

sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");

sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");

sbValid.Append(ctl.ClientID + ".disabled = true;");

// GetPostBackEventReference obtains a reference to a client-side script 
// function that causes the server to post back to the page.

sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));

sbValid.Append(";");

ctl.Attributes.Add("onclick", sbValid.ToString());

}

See this asp.net threadfor more info.

有关更多信息,请参阅此asp.net 线程

Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:

更新:上面的代码将用于在后面的代码中添加 OnClientClick 处理程序。您还可以在 aspx 标记中编写 javascript,如下所示:

<script type="text/javascript">
function disableButton(button)
{
    // if there are client validators on the page
    if (typeof(Page_ClientValidate) == 'function') 
    {
        // if validation failed return false
        // this will cancel the click event
        if (Page_ClientValidate() == false) 
        { 
            return false; 
        }
    }

    // change the button text (does not apply to an ImageButton)
    //button.value = "Please wait ...";
    // disable the button
    button.disabled = true;

    // fire postback
    __doPostBack(button.id, '');
}
</script>

<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png" 
    ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName" 
    OnClientClick="return disableButton(this);" />

回答by Matt Hamsmith

Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.

类似于 Silky 的客户端响应,我通常制作两个看起来相似的按钮,只是第二个按钮被禁用和隐藏。普通按钮的 OnClientClick 交换两个按钮的显示样式,使普通按钮隐藏,禁用按钮显示。

回答by Tarik

The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.

双击功能是服务器端实现,以防止处理可以通过 JavaScript 在客户端实现的相同请求。该功能的主要目的是防止两次处理相同的请求。服务器端实现通过识别重复的请求来做到这一点;然而,理想的解决方案是防止这种情况发生在客户端。

In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.

在发送给客户端允许他们提交请求的 HTML 内容中,可以使用一个小的验证 JavaScript 来检查请求是否已经提交,如果已经提交,防止在线购物者再次提交请求。这个 JavaScript 验证函数将检查全局标志以查看请求是否已提交,如果已提交;不会重新提交请求。如果在服务器上禁用了双击功能,强烈建议 JSP 和 HTML 页面实现此 JavaScript 预防。

The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:

以下示例通过使用表单对象的 onSubmit() 操作防止表单被多次提交:

...
<script>
var requestSubmitted = false;
       function submitRequest() {
              if (!requestSubmitted ) {
                     requestSubmitted  = true;
                     return true;
              }
              return false;
       }
</script>
...

       <FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
              ......
       </FORM> 

回答by Michael Rudner Evanchik

for those who just want to do a quick fix , just hide it and show another button that has no events

对于那些只想快速修复的人,只需隐藏它并显示另一个没有事件的按钮

<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');"  />
<script>
 function hideit() {



        var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
        var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
        if (btn != null)
        {

            btn.style.display = 'none';
            btn2.style.display = 'block'
        }
 }
    </script>