Code Renaissance is about building great teams and great software. By exploring best practices, team interactions, design, testing and related skills Code Renaissance strives to help you create the team and codebase that you've always wanted.

Update Panel, Partial Postback and Javascript

OK, so here's the problem. I have an update panel and after it refreshes I need to run JavaScript to initialize tabs within the panel based on their state before the refresh (partial postback). I tried getting the onload event of an element within the panel to fire and explored a few other options, but nothing I did was successful.

It's at this point I need to send out a big thank you to David Ward at Encosia.com for documenting a simple solution to triggering JavaScript on partial postback client-side initialization. It turns out that Asp.net wires up any JavaScript method named pageLoad() to the Application.PageLoad event so it not only gets called on the initial page load but also on any partial postback. With this fact in hand getting my JavaScript to fire was a snap.

This is my final code:

pageLoad = function()
{
  if(this.isPostBack != true)
  {
    cr.initPage();
    this.isPostBack = true;
  }
  else
  {
    cr.initTabs();     
  }
};

You'll notice that I initially test if this.isPostBack != true, but since it doesn't exist yet it can't be true. This allows the first if block to run, initialize the page and set this.isPostBack to true. All future times the pageLoad function is called will be in post backs. At that point this.isPostBack will return true because my previous setting of this value was preserved through the partial post back and my tab initialization will run.

Again thanks to David for pointing me in the right direction.

4 - What do you think?:

Anonymous said...

Woot! thanks for this simple example. I'm new to web development and was having similar problems, and all I had to do was change one line!

DH said...

Glad it helped.

Anonymous said...

Great example. Got it to trigger on the first load and the first partial postback but not any additional partials after that. Any ideas why that might be?

Thanks,

Chris

DH said...

Chris,

Sorry to take so long to get back to you. It's hard to say what might be wrong without seeing your code... feel free to post it and I'll have a quick look or you can email me at the email address at the bottom of the site.

Thanks for the comment,
Dave