Thursday, February 18, 2010

Check Page.IsPostBack from Javascript

This cannot be done alone from Javascript. We need to use some help from the server file as well.

1. Add Postback check in the server file:

In the page_load of server file, Add this code:

if (!Page.IsPostBack)
{
string Script = "var ranOnce = false;";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitVariable", Script, true);
}

As we know !Page.IsPostBack check restricts execution to enter into the "if" block more than once after page has been loaded. We are declaring a javascript variable "ranOnce" from this block. RegisterClientScriptBlock adds the javascript code add the begining of page script, thats why we are using it because variables should be declared before the javascript function is declared.

2. Write the rest of the code in javascript:

function Prepare() {
if(!ranOnce){
// your code here
ranOnce=true;
}
}

window.onload = Prepare;

Because the function is attached to window.onload, it will run every time, but as we set "ranOnce" to false when the execution entered for the first time it will not execute again.

Now, if page refreshes (not postback), or user navigates back from other page, then from the server side, the "ranOnce" variable will be set to false again, and the function "Prepare" will execute once again.