2015-10-19 220 views
0

我已經創建了一個電子郵件網站表單,用戶可以在其中輸入姓名,電子郵件和消息,然後提交一個按鈕發送。一旦發送電子郵件,頁面上的lblResults將聲明「謝謝。」我想要實現的是,如果頁面被更改,關閉或刷新,則lblResults將返回「」。我能夠完成這項工作,但問題是,當我刷新時,它會重新發送相同的電子郵件。刷新頁面時防止重新提交

在下面的代碼背後我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.IO; 
using System.Net.Mail; 

public partial class Contact : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Session["ClickedLink"] = "Contact"; 

     if (!IsPostBack) 
      Session["Check_Page_Refresh"] = DateTime.Now.ToString(); 
    } 

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

    protected void btnSend_Click(object sender, EventArgs e) 
    { 
     if (Page.IsValid) 
     { 
      string fileName = Server.MapPath("~/App_Data/Contact.txt"); 
      string mailBody = File.ReadAllText(fileName); 
      mailBody = mailBody.Replace("##Name##", txtName.Text); 
      mailBody = mailBody.Replace("##Email##", txtEmail.Text); 
      mailBody = mailBody.Replace("##Message##", txtMessage.Text); 
      MailMessage myMessage = new MailMessage(); 
      myMessage.Subject = "Response from web site"; 
      myMessage.Body = mailBody; 
      myMessage.From = new MailAddress("[email protected]", "Sender Name"); 
      myMessage.To.Add(new MailAddress("[email protected]", "Receiver Name")); 
      myMessage.ReplyToList.Add(new MailAddress(txtEmail.Text)); 
      SmtpClient mySmtpClient = new SmtpClient(); 
      mySmtpClient.Send(myMessage); 

      txtName.Text = ""; 
      txtEmail.Text = ""; 
      txtMessage.Text = ""; 
     } 
     if (ViewState["Check_Page_Refresh"].ToString() == Session["Check_Page_Refresh"].ToString()) 
     { 
      Session["Check_Page_Refresh"] = DateTime.Now.ToString(); 
      lblResults.Text = "Thank you"; 
     } 
     else 
     { 
      lblResults.Text = ""; 
     } 
    } 
} 

請注意,我還沒有學會JS尚未所以如果可能的重點將放在HTML5,CSS3,ASP。 NET或C#。提前致謝。任何建議都會有幫助!

回答

2

處理此問題的模式被稱爲Post-Redirect-Get。 基本上,您不會使用同一個Url進行回覆,因此重複的回帖不會發生。相反,用戶發佈表單,並且POST將重定向回覆爲GET

錯誤方式:

PRG

更好的方式:

enter image description here

More detailed blog post here