如何防止从服务器端双击按钮

时间:2017-02-01 06:00:43

标签: c# asp.net webforms

我在javascript按钮上单击了禁用按钮,它在大多数情况下可以防止双击,但在某些情况下它不起作用所以我想防止从服务器端双击。

 var target = $("#section2");
 $('#myPanel').animate({
   scrollTop: target.offset().top - 100
 }, 700);

在双击场景中,会产生往返两次。在第一次往返行程中没有问题,但是在第二次往返行程中,虽然我用新插入的ID设置了hfid.value,但它显示0并且再次生成重复记录

4 个答案:

答案 0 :(得分:1)

您可以在Session事件处理程序中使用frmSubmit_Click变量,以确保服务器端没有运行提交代码两次:

Form_Load事件中,添加:

Session["isProcessingForm"] = false;

修改frmSubmit_Click事件处理程序,如下所示:

protected void frmSubmit_Click(object sender, EventArgs e)
{
   if(Session["isProcessingForm"])
   {
       return;
   }

   Session["isProcessingForm"] = true;

   if(Convert.ToInt32(hfid.value) == 0)
   {
       // Code of insert
       // then I set hfid.value with newly created id
   }

   //Once form is processed
   Session["isProcessingForm"] = false;
}

如果此应用程序在Web场(多个Web服务器)上运行,则您需要保持会话状态。在ASP.NET WebForms中有几种​​方法可以实现。这里有更多信息:https://msdn.microsoft.com/en-us/library/ms178581.aspx和此处:https://msdn.microsoft.com/en-us/library/ms178587.aspx

答案 1 :(得分:0)

最好的选择是在第一次点击时使用javascript在客户端禁用按钮

答案 2 :(得分:0)

尝试以下方法:它绝对应该有用。

Original Image

答案 3 :(得分:-2)

您可以使用Lock。防止同时多次通话。

private object _lockObj = new object();
protected void frmSubmit_Click(object sender, EventArgs e)
{
    // Here we lock code. When someone else will try to access to this code
    // or in your case double clicked button it will wait until _lockObj
    // is set to free.
    Lock(_lockObj)
    {
        if(Convert.ToInt32(hfid.value) == 0)
        {
        // Code of insert
        // then I set hfid.value with newly created id
        }
    }
}