2016-05-26 65 views
0

我在數據庫中插入一些內容,在按鈕單擊事件時插入數據時,每件事物都正常工作。添加頁面刷新次數儘可能多的行添加

問題是我剛剛點擊按鈕後刷新頁面,然後我注意到,點擊按鈕後,數據插入儘可能多的時間,因爲我刷新頁面。

我該如何解決這個問題? 這是我的按鈕代碼:

protected void btn_AddEdu_Click(object sender, EventArgs e) 
    { 
     hfTab.Value = "edu"; 
     if (ValidateAddEdu()) 
     { 
      emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString()); 
      int imagefilelength = fileupload_edu.PostedFile.ContentLength; 
      byte[] imgarray = new byte[imagefilelength]; 
      HttpPostedFile image = fileupload_edu.PostedFile; 
      image.InputStream.Read(imgarray, 0, imagefilelength); 
      edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray); 
      lbl_eduerr.Text = "Added"; 
      lbl_eduerr.ForeColor = System.Drawing.Color.Green; 
      BindEduGrid(); 

     } 
    } 
+0

不瀏覽器提醒你,當你刷新頁面,你要發送POST再次? – CodeCaster

+0

不,它不警告我。但如果它警告,並且用戶確認它,該行將被插入兩次。我可以阻止它嗎? –

+0

試着把你的代碼包裝在'if(!Page.IsPostBack){}'裏面按鈕點擊 – Ansari

回答

0

添加下面的代碼在你的.cs頁

protected void Page_Load(object sender, EventArgs e) 
{ 
      if (!Page.IsPostBack) 
      { 
       Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); 
      } 
} 


protected void Page_PreRender(object sender, EventArgs e) 
{ 
     ViewState["CheckRefresh"] = Session["CheckRefresh"];  
} 


protected void btn_AddEdu_Click(object sender, EventArgs e) 
{ 
    if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString()) 
    { 
    hfTab.Value = "edu"; 
    if (ValidateAddEdu()) 
    { 
     emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString()); 
     int imagefilelength = fileupload_edu.PostedFile.ContentLength; 
     byte[] imgarray = new byte[imagefilelength]; 
     HttpPostedFile image = fileupload_edu.PostedFile; 
     image.InputStream.Read(imgarray, 0, imagefilelength); 
     edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray); 
     lbl_eduerr.Text = "Added"; 
     //Add this line 
     Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); 
     lbl_eduerr.ForeColor = System.Drawing.Color.Green; 
     BindEduGrid(); 

    } 
    } 
} 
+0

謝謝它的工作:) –