Why jQuery only works once in some ASP.NET pages

I had a strange problem where a simple jQuery expression worked once only on an ASP.NET page. Turned out that .NET UpdateProgress controls on the same page were causing problems with partial page refreshing from AJAX calls.

Code Frameworks Docker

Why jQuery only works once in ASP.NET
by Les Kendall.

I had a strange problem where a simple jQuery expression worked once only on an ASP.NET page. Turned out that .NET UpdateProgress controls on the same page were causing problems with partial page refreshing from AJAX calls.

I had the simplest of jQuery code on a user control:


$(document).ready(function () {

$(‘#mybutton’).click(function () {
$(‘.chartwin’).slideToggle(“slow”);
});

});

First time in, the page displayed and everything looked good. In fact, I went some time before I realised that when the page was partially refreshed by an auto-postback from a dropdown control my button no longer worked.

On further investigation of the parent page, I found that my user control was sitting in a .NET UpdateProgress control section. The UpdateProgress provides a simple means of applying partial page refreshes; it’s a magical thing when it works but I’ve had trouble with them before, interfering with other javascript (including ASP.NET AJAX controls) on the same page.

The solutions can sometimes be quite involved, but in this particular problem I read of a simple solution.

The problem lies with the fact that the jQuery ready(function() only runs once when the page first starts. When the page is partially refreshed (as in an AJAX call) we need to effectively re-wire the jQuery events.

All .NET programmes will know the function PageLoad event very well, but there is an equivalent javascript event too. We can use this to reload our jQuery events each time the page is refreshed. Our code now becomes:


function pageLoad()
{
$(function () {
$('#mybutton').click(function () {
$('.chartwin').slideToggle("slow");
});
});
}

That fixed it for me! The drawback is the hit that we have to load all the jQuery each time the page refreshes or partially refreshes instead of just once. It wasn’t much of a problem for me in this case.

Note that as we’re not checking the DOM is fully loaded (as when using (document).ready), you should add the code to the bottom of the page and after the scriptmanager has been loaded.

I worry when I have to start bodging javascript code because it can be difficult to test and debug. I’ve seen on the web that there are other more sophisticated fixes to this problem which leads me to think that this is not a definitive solution for all problems, so be carelul. If you hear of a better way of doing this, let me know.