1

I have a *.aspx page that contains a text box and a button. When the user enters information in to the textbox and clicks post, it inserts the data into my sql database. The issue is, that if the user hits refresh, it will keep inserting the same data into the database. I am pretty sure the whole "click" method is called, not just the insert call. I tried messing with sessions but it complains. I am not really sure what to do. I am looking for a simple easy fix.

protected void PostButton_Click(object sender, EventArgs e)
{
    string wpost = (string)Session["WallPost"];
    DateTime wtime = (DateTime)Session["WallDateTime"];
    if (txtWallPost.Text.Length > 0 && !wpost.Equals(txtWallPost.Text))
    {
        string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(strCon))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "INSERT INTO [WallTable] ([UserId], [FriendId], [WallPost]) VALUES (@UserId, @FriendId, @WallPost)";
                cmd.Parameters.AddWithValue("@UserId", User.Identity.Name);
                cmd.Parameters.AddWithValue("@FriendId", User.Identity.Name);
                cmd.Parameters.AddWithValue("@WallPost", txtWallPost.Text);
                conn.Open();
                cmd.ExecuteNonQuery();
                Session.Add("WallPost", txtWallPost.Text);
                Session.Add("WallDateTime", new DateTime());
                conn.Close();
                txtWallPost.Text = "";
                LoadWallPosts();
            }
        }
    }
    return;
}
4

4 回答 4

0

添加 Response.Redirect(Request.Url.ToString(), false); 到您的按钮事件,这应该可以解决问题。

于 2013-01-20T21:20:19.380 回答
0

如果它PostButton_Click是按钮上单击事件的服务器处理程序,则仅当用户点击发布按钮时才执行插入代码 - 在刷新的情况下不应发生。

我很确定这还不够 - 确保在您的PostButton_Click方法中放置一个断点,按 F5 以在调试模式下运行,然后查看是否刷新断点。

如果是这样,则意味着:

  1. 您正在 PostButton_Click从其他地方明确调用(Page_Load?)
  2. PostButton_Click被意外设置为页面上某些其他事件的事件处理程序

验证假设 1 和 2 的一种快速方法是运行搜索PostButton_Click并查看您从哪里调用它,或者它是否设置为标记中某个其他元素(可能是您的表单?)的处理程序。

于 2009-04-13T14:22:10.923 回答
-1

if he refreshes or press the back button the post will happen again, thus your page will process the same data thus insert once again.

You have to change your logic

于 2009-04-13T14:02:14.513 回答
-1

插入后最好将客户端重定向到另一个页面,但是,如果您确实需要客户端留在同一页面中,您可以在页面上使用 (bool) 变量来说明插入是否已完成,并且如果之前已经执行过插入逻辑,则跳过它

于 2009-04-13T15:02:44.367 回答