我在asp.net和C#中有一个带提交按钮的表单。表单用于通过电子邮件向网站站长提交评论。 C#代码如下。
但面临一个问题。即刷新页面时,由于回发,它再次在电子邮件中发送评论。我怎么能避免这个?这是代码......
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string body = "";
//body = body + "<html><head></head><body>";
body = body + "Dear Balvignan Team,\r\n";
if (txtComment.Text != null)
{
body = body + "Comment: " + txtComment.Text;
}
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
SendEmail是发送电子邮件的功能。
答案 0 :(得分:0)
在您的page_load活动中
if(page.isPostback==NO)
{
//send an email
}
else
{
//Don't send
}
答案 1 :(得分:0)
您可以使用Page.IsPostBack Property检查是否为回发或页面刷新。
答案 2 :(得分:0)
您可以使用以下选项:
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
Response.Redirect("contact.aspx?success=true");
}
else
{
Response.Redirect("contact.aspx");
}
页面加载
if (!Page.IsPostback)
{
if (Request.QueryString["success"] == "true" )
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
当用户刷新页面(ctrl + r,f5等)将发送给GET请求,而不是POST请求。
编辑其他解决方案
另一种解决方案是使用ViewState:
public bool EmailSent
{
get
{
return ViewState["EmailSent"] != null ? (bool)ViewState["EmailSent"] : false;
}
set
{
ViewState["EmailSent"] = value;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
if (!EmailSent)
{
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
...
EmailSent = true;
}
else
{
...
}
}
}