Monday, December 21, 2009

jQuery: Using a dialog on an ASP.Net UpdatePanel

I recently decided to start using UpdatePanel's in my code.  I know this is not the best way to write an AJAX enabled app, but it was the quickest path to making my product more responsive.  I also decided to integrate the use of jQuery in my app.  Along with that, I have decided to utilize the jQuery Dialog.

At first, it was a little difficult to get my head wrapped around how to best take advantage of this feature, but I eventually developed a process.  I have user controls that are placed on the page in UpdatePanels.  Sometimes those user controls need to pop up a dialog, so I will include the code for the dialog on the user control in a hidden DIV.

Now having a dialog in a DIV is not enough, you have to add javascript to create the dialog from your DIV, that's just how jQuery works, so I include code in an event handler that gets fired every time the UpdatePanel is updated (each user control uses the $(document).one("eventName", function() {}) syntax, but how that works is for another post).

Well I was noticing that I was having problems on the post backs when I had a dialog that was created from the user controls.  As it turns out, the problem was coming from the fact that each time the user control was refreshed, it was loading the jQuery Dialog into the DOM.  That meant that every post back puts a new copy of the dialog into the DOM causing problems with the values that post back to the server (not to mention a potentially bad memory leak).

I finally ended up with a solution that works great.  I have code that checks the DOM for the existence of the dialog prior to creating it and if it exists, I remove the first one.  Now this is not a problem for me, but if the dialog were to get updated in the post back, you would probably want to remove the last one and not the first one since the first one in the DOM is probably the one updated from the post back.

var dialogs = $("dailogSelector");
    if (dialogs.length == 2) {
        $(dialogs[0]).remove(); 
    }
}

This was something that after finding it seemed very obvious.  It was completely obvious once I fired up FireBug and saw that I had multiple copies of the dialog in memory.  However, prior to that, it seemed like there was some gremlin somewhere in the page life cycle stealing my post back values and it was very frustrating.  I only hope this post saves someone the frustration it caused me!