jQuery and ASP.NET AJAX Postbacks or Partial Page Rendering with UpdatePanel’s

Recently I was working on a web application that made use of the new jQuery library for client-side UI enhancements. While being fairly new at working with ASP.NET’s AJAX I felt pretty confident that I would be able to make it all work to my advantage considering I have a good understanding/experience level with ASP.NET server-side and working with JavaScript and DHTML on the client-side in the past. ASP.NET AJAX is basically just the more intelligent way to get the best of both worlds; server-side but with the normal client-side dynamics.

Anyway enough of my ramble. The problem I faced was when it came to using the jQuery library with an UpdatePanel; UpdatePanel’s are server-side controls which allow you to process server-side code dynamically without reloading a page, the process is normally referred to Partial Page Rendering.

Now when I attach my code to a event handler so that it would fire in real-time within the UpdatePanel it would cause a Postback to occur. This is what I wanted as the page’s ViewState needed to be updated among other things. The problem occurred when the first Postback occurred, after this my jQuery library was no longer attaching itself back to the form controls. I lost my ability to fire any other functions from jQuery.

In short I believe according to what I read about this issue, is that due to the way ASP.NET AJAX wires up its JavaScript for partial page rendering the OnLoad(); function is not re-executed and therefore any jQuery library’s will not re-initialise. jQuery documents this limitation on their reference guide. So what was my solution, well it was simple. Fortunately ASP.NET AJAX lets you attach additional OnLoad code for further processing. The best part is that it re-initialises on every Postback! Other solutions I found were talking about re-writing a OnLoad(); function which was inside the UpdatePanel but the limitation there is that JavaScript on the client-side uses the last occurrence of OnLoad(); and discards the previous occurrences thus is no good and isn’t as dynamic as my solution.

<script type="text/javascript">

Sys.Application.add_load(funNewOnLoad);
function funNewOnLoad()
{
  

// Code here will execute onLoad plus on every UpdatePanel postback. E.g. Place jQuery here.


}

</script>

Rating 3.00 out of 5
%d bloggers like this: