返回并重新加载页面时显示不需要的服务器端警报消息

server side alert message that shows unwanted when get back and reload the page

本文关键字:不需要 显示 服务器端 消息 新加载 加载 返回      更新时间:2023-10-03

我有一个提交按钮,下面是onClick事件中的代码:

protected void btnSubmit_Click(object sender, EventArgs e)
{
...
ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Submitted')", true);
}

此代码有效。

但问题是,当用户通过以下方式转到下一页时:

Response.Redirect("page2.aspx");

当点击退格返回第1页时,

在重新装载之前,

出现以下消息框!!

this problem happened again when we refresh(F5) the page1 after submiting

我将如何解决这个问题?

我试过了:

 1. if(isPostback)// before the alert
 2. string message = "Submitted";
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<script type = 'text/javascript'>");
    sb.Append("window.onload=function(){");
    sb.Append("alert('");
    sb.Append(message);
    sb.Append("')};");
    sb.Append("</script>");
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());

在这种情况下,您可以实现一个特殊的代码块来检测浏览器刷新为

private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
    object[] AllStates = (object[])savedState;
    base.LoadViewState(AllStates[0]);
    refreshState = bool.Parse(AllStates[1].ToString());
    if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
        isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
    Session["ISREFRESH"] = refreshState;
    object[] AllStates = new object[3];
    AllStates[0] = base.SaveViewState();
    AllStates[1] = !(refreshState);
    return AllStates;
}

在按钮提交你可以做它作为

protected void btn3_Click(object sender, EventArgs e)
{
    if (isRefresh == false)
        {
            Insert Code here
        }
}