2012-10-06 52 views
2

你好,我有问题,每当我按下刷新按钮,它不断添加:/我如何防止它?它是我的2搞清楚了这一点的一天,我失败了:(防止每当用户点击刷新时添加新记录

protected void Button1_Click(object sender, EventArgs e) 
     { 
      //Instantiate the connection with the database 
      using (SqlConnection myConnection = new SqlConnection("user id=username;" + 
                    "password=password;" + 
                    "trusted_connection=yes;" + 
                    "database=DataBaseConnection;" + 
                    "connection timeout=30;")) 
      { 
       //Open the Connection object 
       myConnection.Open(); 

       //Instantiate a SQL Command with an INSERT query 
       SqlCommand myCommand = new SqlCommand("INSERT INTO BasicInfo (Firstname,Surname) Values(@a,@b);", myConnection); 

       if (TextBox1.Text !=null && TextBox2.Text != null) 
       { 
        //Texbox 
        myCommand.Parameters.AddWithValue("@a", TextBox1.Text); 
        myCommand.Parameters.AddWithValue("@b", TextBox2.Text); 

        //Execute the query 
        myCommand.ExecuteNonQuery(); 
       } 
       else 
       { 
        //Code HEre? 
       } 
+1

你不能使用'!IsPostBack()' – FosterZ

+0

@FosterZ:在这种情况下,他不能。 Button1_Click事件由回发触发。 – rsbarro

+0

这里不是一个ASP .NET开发者,但是什么时候'TextBox1.Text'永远是'null'?你的意思是与'String.Empty'进行比较还是使用'String.IsNullOrEmpty'来代替? http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.text.aspx –

回答

4

一个来处理这个问题的方法是在Button1_Click活动结束做Response.Redirect回到原来的页面。该Response.Redirect将使浏览器做一个GET请求的页面,所以如果用户点击F5,他们只会重做GET(而不是再次POST表单)。

这种方法有时被称为Post/Redirect/Get模式。一个相当不错的写法: http://blog.andreloker.de/post/2008/06/Post-Redirect-Get.aspx

+0

伟大的链接,谢谢:) – IrishChieftain

0

One stra为了防止多次处理东西,tegy为每个表单分配一个标记,作为一个隐藏字段。

一旦完成响应提交表单所需的任何处理,就会撤消该令牌。

或者,将令牌保存为处理的一部分,并在处理中添加一个检查以首先查看该令牌是否已被使用。

这有助于您可能收到两次请求的任何情况,例如,如果用户双击按钮或链接。