Asp.Net SQL刷新页面重复插入?
问题描述:
我有一个* .aspx页面,其中包含一个文本框和一个按钮。当用户输入信息到文本框并点击文章时,它会将数据插入到我的sql数据库中。问题是,如果用户点击刷新,它将继续向数据库中插入相同的数据。我很确定整个“点击”方法被调用,而不仅仅是插入调用。我试着搞会议,但它抱怨。我不知道该怎么做。我正在寻找一个简单的解决方法。Asp.Net SQL刷新页面重复插入?
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;
}
答
如果他刷新或按后退按钮后会再次发生,因此,你的页面会处理由此相同的数据再次插入。
你必须改变你的逻辑
答
如果PostButton_Click
是您为按钮的Click事件的服务器处理,然后插入只有当用户点击后按钮的代码应和执行 - 它不应该在的情况下发生刷新。
我敢肯定是不够的 - 以确保将断点在你PostButton_Click
方法,按F5在调试模式下运行,看看断点获取与刷新击中。
如果是这样就意味着:
- 您呼叫从 别的地方(?
Page_Load
)明确PostButton_Click
-
PostButton_Click
却意外 集作为事件处理程序 页面上的其他一些 事件
快速验证假设的方法1 & 2是ru n搜索PostButton_Click
并查看您在哪里调用它,或者如果它设置为标记中某个其他元素(可能是您的表单?)的处理程序。
答
最好在插入后将客户端重定向到另一个页面,但是,如果您确实需要客户端停留在同一页面中,则可以在页面上使用(bool)变量来指定插入是否存在如果已经执行,则跳过插入逻辑
答
Add Response.Redirect(Request.Url.ToString(),false);到你的按钮事件,并应该解决问题。
可能重复[如何防止重复回发混淆我的业务层](http://stackoverflow.com/questions/481564/how-to-prevent-repeated-postbacks-from-confusing-my-business-layer ) – 2011-09-04 13:59:54