Tuesday, March 24, 2009

javascript code not working when using updatepanel?

I have some javascript code gets executed when window.onload is fired. It basically modifies the appearance of my server controls. Everything works fine before I placed my server controls in an updatePanel(ASP.NET).

When the page got partially rendered(i.e. I clicked the button which is inside the updatePanel to cause a postback), the javascript code didn't work anymore.

I haven't delve into this issue to completely understand this, but I found a solution. It is to use PageRequestManager to register the javascript function I'd like to call each time there is a postback(async or sync). The code is:
function load() {
Then add onload="load()" to body tag.

For reference:http://msdn.microsoft.com/en-us/library/bb311028.aspx(Sys.WebForms.PageRequestManager Class)


Xiaoguang said...

If we are to register the client script on the server, we can use ScriptManager.RegisterClientScriptBlock method (instead of ClientScript.RegisterClientScriptBlock method as we use in full postback).

Xiaoguang said...

Also, if we use RegisterClientScriptBlock to register script, each time a postback happens (full or partial), we need some way to register it again. For example, if we put the register logic inside "if(!IsPostBack)" block in Page_Load, the script will only work for the first time the page is loaded.