许多 Web 开发人员在其 Web 应用程序中面临的最常见问题之一是,重复记录会在页面刷新时插入到数据库中。如果网页包含一些文本框和一个将文本框数据提交到数据库的按钮。在这种情况下,当用户在文本框中插入一些数据并单击提交按钮时,它会将记录保存到数据库中,然后如果用户立即刷新网页,那么相同的记录会再次保存到数据库中,因为有没有可以用来验证数据是否存在的唯一键,从而防止多次插入。
从这个行为我们可以肯定地知道,在页面新鲜的按钮点击事件被触发。
为了避免这个问题,我们可以尝试下面讨论的这种方法。
在页面加载事件中,将日期/时间戳保存在会话变量中,当页面首次加载时,会话变量将填充当前日期/时间,如下所示:
*void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
会话[“更新”] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}*
在页面的 PreRender 事件中,一个 ViewState 变量被设置为 Session 变量的值,如下:
void Page_PreRender(object obj,EventArgs e)
{
ViewState["update"] = Session["update"];
}
然后在运行数据库 INSERT 命令之前将这两个值相互比较。
如果它们相等,则允许执行该命令并使用当前日期/时间更新 Session 变量,否则将绕过该命令,如下所示:
void btnSubmit_Click(object obj, EventArgs e)
{
string name = "";
string qualification = "";
if (Session["update"].ToString() == ViewState["update"].ToString())
{
if (txtName.Text != "" || txtName.Text != null)
{
name = txtName.Text.ToString();
}
if (txtQualification.Text != "" || txtQualification.Text != null)
{
qualification = txtQualification.Text.ToString();
}
//--- Insert data function should be execute here
string strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name + "','" + qualification + "')";
SqlConnection ANConnection = new SqlConnection(ConnectionString);
ANConnection.Open();
SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
ANCommand.ExecuteNonQuery();
ANConnection.Close();
ANConnection.Dispose();
//--End of save data
lblMessage.Text = "Inserted Record Sucessfully
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMessage.Text = "Failure – Due to Page Refresh";
txtName.Text = "";
txtQualification.Text = "";
}
}