如何在window.onunload中确定PostBack值

How can i determine PostBack value in window.onunload?

本文关键字:PostBack onunload window      更新时间:2023-09-26

在我们的项目中,我们在用户离开页面后删除了一些内容。我们正在使用window.unload事件来执行此操作。

window.onunload = function() {
  // delete something
}

我们通常使用按钮、链接按钮。。等等,所以我们不需要检查Page.IsPostBack属性。

今天,我们意识到我们使用了UpdatePanel中的一些按钮,这种情况产生了一些错误。之后,我们决定更改我们的方法,在页面顶部定义了一个全局变量(var_isPostBack=false),并:

window.onunload = function() {
  if (_isPostBack) {
    _isPostBack = false;
    return;
  }
  // delete something
}

尽管我在Page_Load中设置了g_isPostBack,但g_isPostBack没有改变。我尝试了"RegisterClientScriptBlock"、"RegisterOnSubmitStatement"answers"RegisterStartupScript"方法。在onunload事件之前调用了Register方法,但在onunlog事件触发之后设置了_isPostBack。。。

if (IsPostBack)
{
  Control c = MyClass.GetPostBackControl(this);
  bool inUpdatePanel = ControlParentForUpdatePanel(c);
  if (!inUpdatePanel)
  {
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
  }
}

有人帮我吗?

这就是诀窍。。。

如果您将onsubmit属性添加到表单标签:

<form id="form1" onsubmit="return yourPostBack()">

然后编写自己的函数:

function yourPostBack()
{
  _isPostBack = true;
  return true;
}

最后在页面加载中:

if (IsPostBack)
{
  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}

使用此方法,您可以在窗口中了解它是否是回发的。卸载

,我希望我在这里走在正确的轨道上

据我所知,OnUnload()是ClientSide,因此您没有服务器对象您可以做的是将值保存在一个隐藏字段中。

由于我习惯了PHP,你甚至可以将值嵌入Javascript变量中不知道这是否适用于ASP.NET:

<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>

转换为

<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>

但同样的事情也可以用<asp:Label/>我确信。。。