方法的原理就是在每次处理请求(比如按钮的回发事件)后,都随机生成一个字符串,这个字符串分别存放在Session和响应页面中,在开始处理用户请求时,判断传上来的字符串和Session中的字符串是否匹配,如果是重复提交,客户端传上来的字符串就是个旧的,显然和Session中的字符串不同。
也可以自定义一个控件方便调用。
具体步骤如下:
1、在进入页面的时候,随机生成个字符串,这个保存到session并且写到页面的控件上。
2、在提交后,判断你的session中的字符串和提交上来的字符串是否相同,相同就进行处理;不相同说明是重复提交,不进行相关处理,写个alert提醒不能重复提交。
3、然后重复第1步。
下面是测试页面的源代码。
test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:HiddenField ID="HidSign" runat="server" />
</div>
</form>
</body>
</html>
test.aspx.cs
using System;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UpdateSign();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["HidSign"].ToString() == HidSign.Value)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "startup", "alert('更新成功!')", true);
UpdateSign();
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "startup", "alert('请勿重复提交!');", true);
UpdateSign();
}
}
private void UpdateSign()
{
HidSign.Value = DateTime.Now.ToString("ffffff");
Session["HidSign"] = HidSign.Value;
}
}
如果觉得session耗资源,也可以声明全局的静态变量,用他替换session
本文作者:网友 来源:网络 http://hi.baidu.com/djcm99/blog/
CIO之家 www.ciozj.com 微信公众号:imciow