如果更改或刷新页面,则清除标签

时间:2015-10-21 18:38:00

标签: c# asp.net html5 email session-variables

我创建了一个电子邮件表单,当用户点击提交时。如果刷新页面,页面将重定向到同一页面以防止重新提交。页面重定向到自身后,标签会显示“谢谢”。问题是,当我刷新页面或转到另一页并返回时,标签仍显示“谢谢”,而不是“”。当我刷新页面或更改页面或更好的解决方案时,有没有办法清除会话[“结果”]?提前谢谢。

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

        lblResults.Text = "";

        if (!IsPostBack)
        {
            lblResults.Text = Session["Results"].ToString();
        }       
    }

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

        lblResults.Text = "Thank you";
        Session["Results"] = lblResults.Text;
        Response.Redirect("Contact.aspx");

    }
}

2 个答案:

答案 0 :(得分:1)

您可以在重定向的查询字符串中发送消息。

protected void btnSend_Click(object sender, EventArgs e)
{
    // ...

    Response.Redirect("Contact.aspx?msg=Thanks");

}

和PageLoad

protected void Page_Load(object sender, EventArgs e)
{
    Session["ClickedLink"] = "Contact";

    lblResults.Text = "";

    if (!IsPostBack)
    {
        if (Request.QueryString["msg"] != null) 
            lblResults.Text = Request.QueryString["msg"];
    }       
}

答案 1 :(得分:1)

另一个解决方案是在使用后添加一行来清除会话变量:

protected void Page_Load(object sender, EventArgs e)
{
    Session["ClickedLink"] = "Contact";

    lblResults.Text = "";

    if (!IsPostBack)
    {
        lblResults.Text = Session["Results"].ToString();

        Session["Results"] = null;
    }       
}

在QueryString中,用户可以手动插入值以在标签中显示。