Asp.Net上刷新,重复后插入...应该只有一个职位 [英] Asp.Net on refresh, a duplicate post is inserted...should only be one post
问题描述
我有一个的asp:文本框,其允许用户输入信息。当用户点击的ASP:按钮,它插入从文本框中的文本到我的SQL数据库,然后重定向回页面。如果用户点击刷新,从按钮的事件被再次调用。我必须纠正这种以便它不再被调用或不重新发布的信息。
保护无效PostButton_Click(对象发件人,EventArgs的发送)
{
如果(txtWallPost.Text.Length大于0)
{
串STRCON = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[\"SocialSiteConnectionString\"].ConnectionString;
使用(SqlConnection的康恩=新的SqlConnection(STRCON))
{
使用(CMD的SqlCommand = conn.CreateCommand())
{
cmd.CommandText =INSERT INTO [WallTable]([用户ID],[FriendId],[WallPost])VALUES(@UserId,@FriendId,@WallPost);
cmd.Parameters.AddWithValue(@用户ID,User.Identity.Name);
cmd.Parameters.AddWithValue(@ FriendIdUser.Identity.Name);
cmd.Parameters.AddWithValue(@ WallPost,txtWallPost.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
txtWallPost.Text =;
LoadWallPosts();
的Response.Redirect(〜/ UserPages / UserProfile.aspx观点=?+墙);
}
}
}
返回;
}
经典的问题,采用了经典的解决方案:重定向后门柱。你只需要处理POST之后用户到另一个页面(或同一页面...)重定向 - 这样当他们击中刷新,最后一次请求(以及重复的)将是一个GET
见:
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;
}
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:
- Refresh the page after a postback action in asp.net
- How do I use the "Post/Redirect/Get" a.k.a. "Redirect after Post" with asp.net
- Page Refresh Causes Duplicate POST in ASP.NET Applications
- Curing the "Back Button Blues"
这篇关于Asp.Net上刷新,重复后插入...应该只有一个职位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!