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.

9 comments:

Anonymous said...

偉大的致富萬能之鑰,正是幫你充分掌握自己心志所必須的自律自制..................................................

Anonymous said...

After a storm comes a calm. ....................................................

pass said...
This comment has been removed by a blog administrator.
Anonymous said...

Actions speak louder than words. ........................................

Anonymous said...

Many a little makes a mickle.......................................................

Anonymous said...

thank you for you to make me learn more,thank you∩0∩

Anonymous said...

your artical is so funny!! it make me so happy!! ........................................

Anonymous said...
This comment has been removed by a blog administrator.
許美玉 said...
This comment has been removed by a blog administrator.