简体   繁体   中英

Run javascript on the first page load

I only want to run a javascript method on the page load the 1st time only. If there is a postback I do not want to run that method again.

This method is setting the defaults to certain textboxes.

If I add an onLoad to the body element it runs it each time on the postback . I've tried a ClientScript.RegisterStartupScript but that too runs the method on the postback as well.

Am I going to have to do it old school where I have to increment a hidden value and check that each time?

Try defining the method within your Page_Load event using the IsPostBack property to determine if it is the initial load or not :

protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
     { 
         // It is the initial load, call your script
         ClientScript.RegisterStartupScript(...);
     }
}    

The Page_Load event will be called every time that your page is loaded, regardless of a PostBack or not. It will only ever be false on the initial load, so if you place your call within there, it should only execute the script a single time.

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