Peter Morlion logo


jQuery, ASP.NET and subscribing to (pre-)postbacks

ASP.NET (WebForms) has a concept of postbacks. This is not entirely the same a submitting the current form. A LinkButton for example, when clicked, will call a __doPostBack javascript function which was added by ASP.NET.

This means that you can’t always subscribe to the ‘submit’ event with jQuery:

$('form').on('submit', function() {});

You might want to subscribe to the postback because, just before calling the server, you need to fill some hidden field. At least, that was my case.

So, what we need is an event to subscribe to. This can be done thanks to the magic of javascript and the fact that you can replace functions on the fly:

var old__doPostBack = __doPostBack;
__doPostBack = function (eventTarget, eventArgument) {
    old__doPostBack(eventTarget, eventArgument);

What we do here is simply put the __doPostBack function in a variable and the __doPostBack function with our own logic. That logic consists of raising a ‘beforePostBack’ event and then calling the actual post back logic.

To be able to reuse this simple logic, I created a jQuery plugin (which was interesting in its own), hosted on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *