I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).
Basically, I need to check for IsPostBack in JavaScript.
Thank you.
Server-side, write:
if(IsPostBack) { // NOTE: the following uses an overload of RegisterClientScriptBlock() // that will surround our string with the needed script tags ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true); }
Then, in your script which runs for the onLoad, check for the existence of that variable:
if(isPostBack) { // do your thing }
You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.
There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:
if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
or
if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With