刷新页面时防止重新提交

Preventing resubmission when page is refreshed

我创建了一个电子邮件网站表单,用户可以在其中输入他们的姓名、电子邮件和消息,然后提交一个按钮进行发送。发送电子邮件后,页面上的 lblResults 将显示 "Thank you." 我想要实现的是,如果页面发生更改、关闭或刷新,lblResults 将显示 return“”。我能够完成这项工作,但问题是当我刷新时,它会重新发送同一封电子邮件。

下面是我后面的代码:

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 = "";
        }
    }
}

请注意,我还没有学过 JS,所以如果可能的话,重点会放在 HTML5、CSS3、ASP.NET 或 C# 上。提前致谢。任何建议都会有所帮助!

处理此问题的模式称为 Post-Redirect-Get。 本质上,您不会使用相同的 Url 进行响应,因此不会发生重复的 post 返回。相反,用户 post 的表单和 POST 响应重定向到 GET

错误方式:

更好的方法:

More detailed blog post here