简体   繁体   中英

How can i determine PostBack value in window.onunload?

In our project we are deleting something after the user left the page. We are using window.unload event for doing this.

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

We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.

Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:

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

  // delete something
}

Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...

if (IsPostBack)
{
  Control c = MyClass.GetPostBackControl(this);
  bool inUpdatePanel = ControlParentForUpdatePanel(c);

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

Is there anyone to help me?

that's the trick...

if you add onsubmit attribute to your form tag:

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

and than write your own function:

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

and finally in the page load:

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

with this method you can understand that it is postback or not, in window.onunload

I hope i am on the right track here,

As i understand, the OnUnload() is ClientSide, and therefore you don't have the server objects what you can do... is save the value in a hidden field.

As i am used to PHP you can even embed the value in a Javascript variable Dont know if this applys to ASP.NET:

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

translates to

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

But same thing can be done with <asp:Label /> , i am sure...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM