.net C# 利用Session防重复点击防重复提交

时间:2022-01-20 06:40:47

<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<%--利用插入和显示数据量特别大的一张表来模拟网络卡的情况--%>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="Id" DataSourceID="ObjectDataSource1" PageSize="100"
            AllowPaging="True">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True"
                    SortExpression="Id" />
            </Columns>
        </asp:GridView>

</div>
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
        DeleteMethod="Delete" InsertMethod="Insert"
        OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
        TypeName="DataSet1TableAdapters.testbeizhuTableAdapter" UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="String" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Id" Type="String" />
        </InsertParameters>
    </asp:ObjectDataSource>
    </form>
</body>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session["fangchongfu"] = DateTime.Now.ToString();
        }
    }

protected void Button1_Click(object sender, EventArgs e)
    {
        DateTime time1 = DateTime.Now;
        DateTime lastTime = Convert.ToDateTime(Session["fangchongfu"].ToString());
        TimeSpan ts = time1 - lastTime;
        if (10 > ts.TotalSeconds)//小于10秒,则判定为重复提交
        {
            return;
        }
        Session["fangchongfu"] = DateTime.Now.ToString();

//利用插入和显示数据量特别大的一张表来模拟网络卡的情况
        DataSet1TableAdapters.testbeizhuTableAdapter bzAda = new DataSet1TableAdapters.testbeizhuTableAdapter();
        bzAda.InsertQuery();

GridView1.DataSourceID = "ObjectDataSource1";
        GridView1.DataBind();

DateTime time2 = DateTime.Now;

Label1.Text = "用时:" + ts.TotalSeconds.ToString() + ",当前时间:" + DateTime.Now.ToString();
    }
}