How to prevent a user from resubmitting a form?

我怕爱的太早我们不能终老 提交于 2019-12-01 22:10:56
Aristos

Here is a very simple example, where I use a static variable on page and avoid database.

the asp.net page is

<asp:Literal runat="server" ID="txtInfos"></asp:Literal><br />
<asp:TextBox runat="server" ID="txtEmail"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />/>

and the code behind.

static Dictionary<string, DateTime> cLastSubmits = new Dictionary<string, DateTime>();

private static readonly object syncLock = new object();

protected void Button1_Click(object sender, EventArgs e)
{
    DateTime cWhenLast;

    lock (syncLock)
    {
        var cNowIs = DateTime.UtcNow;
        if (cLastSubmits.TryGetValue(txtEmail.Text, out cWhenLast))
        {
            if (cWhenLast > cNowIs )
            {
                txtInfos.Text = "Please contact us again after 10 seconds";
                return;
            }
            else
            {
                // ok I let him submit the form, but note the last date time.
                cLastSubmits.Remove(txtEmail.Text);
            }
        }

        foreach(var DelMe in cLastSubmits.Where(x => cNowIs > x.Value).ToList())
            cLastSubmits.Remove(DelMe.Key);

        // if reach here, note the last datetime of submit            
        cLastSubmits.Add(txtEmail.Text, cNowIs.AddSeconds(10));
    }

    // and submit the form.
    txtInfos.Text = "thank you for submit the form";
}

Some notes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!