views:

495

answers:

2

I have a asp:textbox that allows a user to enter information. When the user clicks the asp:button, it inserts the text from the textbox into my sql database, and then redirects back to the page. If the user hits refresh, the event from the button gets called again. I need to rectify this so that it no longer gets called or it doesn't repost the information.

protected void PostButton_Click(object sender, EventArgs e)
{
    if (txtWallPost.Text.Length > 0)
    {
        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();
                conn.Close();
                txtWallPost.Text = "";
                LoadWallPosts();
                Response.Redirect("~/UserPages/UserProfile.aspx?view="+"wall");
            }
        }
    }
    return;
}
+4  A: 

Classic problem, with a classic solution: Redirect After Post. You just need to redirect the user to another page (or the same page...) after processing the POST - that way when they hit refresh, the last request (and the one to be repeated) will be a GET.

See:

Shog9
A: 

I ended up just adding a session id for the wall post text. In the post method, it checks to make sure the textbox text, is different from that of the session text. On refresh it clears out the session and therefore works fine.

Not a very elegant solution. Take a look at Shog9's answer.
roosteronacid
Even when I did redirect to the page after posting, it would save the button event. So if a user hit refresh even after redirecting, it would still repost the information.