Friday, September 23, 2011

ClientScript.RegisterArrayDeclaration doesn't play nice with Upload Panels

Found a new one today!

I had a problem where some javascript arrays were being initialized by ClientScript.RegisterArrayDeclaration on the server side ASP.NET code.  This worked great initially as the array needed to be loaded up during the first call to the page.

However, I got user requests to add more features to the page including adding new elements to the list that that array would populate.  Of course, they don't want screen flicker on the page either, so no full postbacks.  I assumed that by just doing a normal postback, the array registration code would work fine and everything would move forward.

Turns out, if the declaration is part of controls inside of update panels, ClientScript.RegisterArrayDeclaration won't update the array.  It will look to the javascript after the partial postback just as it did before.

It took me a long time to run this down, but in .NET 4, there is a new animal called ScriptManager.RegisterArrayDeclaration that is built to play nice with UpdatePanels.  So, I quickly changed the ClientScript to ScriptMangager, and sweet!  The array would get updated.

But wait, there's more!  Now, the array gets updated but the old data doesn't get rebuilt.  It just builds on top of itself, adding the same elements to the array each postback.  Bad!

So to solve, I added code to set the array to null prior to all the array declaration code:

ScriptManager.RegistlerClientScriptBlock(me.page, me.page.gettype, "code","array = null;",true)

This would clear the array then reload it.

1 comment: