Previously I thought this was not possible, since the ASP.NET postback involves POST-ing the all-encompassing ASP.NET form, but I am here to tell you, that it is indeed possible to do a postback to a new window or even a popup (created with window.open). In fact, it is surprisingly simple. All you really have to know is that the “target” attribute you know from anchors (links) works exactly the same way for forms!

Once I realized that, hijacking the postback mechanism was easy as the proverbial pie. You start out with a small piece of JavaScript that might look something like this:

function CustomPostBack(controlID, argument, target, popup) {
    var oldTarget;
    if (target != null || popup != null) {
        oldTarget = theForm.target;
        theForm.target = target;
    }
    if (popup != null) {
        window.open('', popup.name, 'width=' + popup.width + ',height=' + popup.height);
        theForm.target = popup.name;
    }

    __doPostBack(controlID, argument);

    if (target != null || popup != null) {
        theForm.target = oldTarget;
    }
}

Let me start by explaining the function parameters:

  • controlID: The unique ID (Control.UniqueID) of the control that will be receiving the postback event. This control has to implement the IPostBackEventHandler interface which defines the void RaisePostBackEvent(string eventArgument) method.
  • argument: The string argument that is passed to the control’s postback event handler.
  • target: The value for the HTML “target” attribute. Use “_blank” to post back to a new window or null if you want to post to a popup window.
  • popup: JSON structure of the form { name: name of the popup, width: width of the popup, height: height of the popup }. If “popup” is not null, the target argument is ignored.

The rest is fairly straight forward. We start by storing the form’s original target so that we can restore it in the end. If we don’t use a popup as target, we set “theForm”‘s target to whatever value is passed in to the function (btw: “theForm” is defined by the regular ASP.NET initialization script). If we want to use a popup as postback target, we first open a new window with the given name and then set the form’s target to that window’s name. This causes the POST to be sent to the popup window. Once the target is properly set, we do a regular ASP.NET post back and restore the original form target – if we don’t do that, all the “normal” postbacks would also be sent to the new window or popup and we don’t want that.

There you go, it’s as simple as that. This works in all browsers that I have tested (FF, Chrome, IE9 and it even works in IE9’s “broken mode”) and is as far as I can tell standard HTML compliant.

Hope this saves somebody some time.

Leave a Reply

Your email address will not be published.

*