Skip to main content
 首页 » 编程设计

c#之我如何确定 window.onunload 中的 PostBack 值

2024年02月23日19bonelee

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

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

我们通常在 UpdatePanel 中使用按钮、链接按钮等,因此我们不需要检查 Page.IsPostBack 属性。

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

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

尽管我在 Page_Load 中设置了 g_isPostBack,但 g_isPostBack 并没有改变。我尝试了“RegisterClientScriptBlock”、“RegisterOnSubmitStatement”和“RegisterStartupScript”方法。在 onunload 事件之前调用了注册方法,但是在 onunload 事件触发之后设置了 _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); 
} 

通过这个方法可以理解是不是postback,在window.onunload中