I have created an email website form where user inputs their name, email, and message then submit a button to send. Once the email is sent, the lblResults on the page will state "Thank you." What I want to achieve is that if the page is changed, closed, or refreshed, the lblResults would return "". I was able to make this work but the problem is that when I refresh, it would resend the same email.
In the following is the code to my code behind:
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("intern2@gmail.com", "Sender Name");
myMessage.To.Add(new MailAddress("intern2@gmail.com", "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 = "";
}
}
}
Please note, I haven't learn JS yet so if possible the focus would be on HTML5, CSS3, ASP.NET, or C#. Thanks in advance. Any suggestions would help!
The pattern to deal with this is known as Post-Redirect-Get . Essentially you don't respond using the same Url so that the duplicate post back cannot happen. Instead the user posts the form and the POST
responds with a redirect to a GET
.
Wrong Way:
Better Way:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.