Pro-Tip: jQuery Event Binding and ASP.NET UpdatePanels

11 September 2012

If you've bound some events (like a keypress to a textbox) within an ASP.NET update panel, this will work the first you try it, but not on subsequent times.

Why? Well, as part of its operation, the ASP.NET UpdatePanel replaces the entire html content of the panel, invalidating your bound events. Fortunately, you can instruct ASP.NET to bind subsequent events with the PageRequestManager, while still having your initial event bound via $(document).ready().

$(document).ready(function() {
    // bind your jQuery events here initially
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function() {
    // re-bind your jQuery events here
});

Moral of the story: if your jQuery event is only working on the first postback and not subsequent ones, it's likely you'll need to rebind the events with the PageRequestManager. Note that this only applies for Javascript that binds directly to elements, so the .on() / .delegate() jQuery methods are not affected by the UpdatePanel's HTML reconstitution.

(Again - how did we ever do anything before the internet / StackOverflow?)

Tags: asp.net, events, UpdatePanel, jQuery

Add a Comment

No Comments