2012-10-06 51 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爲每個表單分配一個標記,作爲一個隱藏字段。

一旦完成響應提交表單所需的任何處理,就會撤消該令牌。

或者,將令牌保存爲處理的一部分,並在處理中添加一個檢查以首先查看該令牌是否已被使用。

這有助於您可能收到兩次請求的任何情況,例如,如果用戶雙擊按鈕或鏈接。