Friday, August 15, 2008

Dynamic Javascript in an Update Panel

If you are using an Ajax UpdatePanel in ASP.NET and you have a control that renders javascript, that javascript will not change when on a partial postback.  For example, I have a Repeater control that loops though so GEO points and outputs javascript to add PushPin to a Virtual Earth map.  If a partial postback is called, and the Repeater rebinds it recreates the javascript, however on the client side the ScriptManager just replaces the UpdatePanel innerHTML with then new code.  It doesn't tell the javascript engine to reparse that code and recreate the functions that are being replaced.  To solve this problem I had to write some javascript client code that would parse the return, and move my <SCRIPT> tags to the head of the page.  This "woke up" the javascript engine and the new functions where recompiled.

How to hook it up:

1) The first thing to do is to tell the ScriptManager to parse the innerHTML of the UpdatePanel and move all script blocks to the head of the page (note: you need to have a page head).  You can do this like this:


2) Next you need to add a function that call EndRequestHandler that will call the parser, like this:

function EndRequestHandler(sender,args){ParseScript($get('UpdatePanelId'));};

Mine looks like this:

Page.ClientScript.RegisterStartupScript(this.GetType(), "EndRequestHandler", "function EndRequestHandler(sender,args){ParseScript($get('" + updatePanel.ClientID + "_Container'));};\r\n", true);

Not that the ParseScript function traverses the controls in the page and find childern with the tag name of <SCRIPT>, so I wanted to start with a UpdatePanel parent, and since the id is dynamically generated, I need to add the EndRequestHandler client side javascript from the server.

3) Next write ParseScript to traverse the childern and move all SCRIPT tags to the head, I will let you write your own code, cause this is QED.


1 comment:

  1. Hi, definitely the problem I am suffering. Thanks for working it all out and publishing it.

    It's a shame you didn't post the QED code for 3 for someone like me who hasn't done it before and it isn't QED. Still I can Google....