The problem
You have a submit Button which normally postback and make result come to the same page. Now you want to direct the result output to a new window making use of the '_blank' code, but still wants the original page to stay as is.
This is especially usefull, when you want to have an asp:Button to let the user download the viewed data as an Excel file, while still having the active page ready for more work.
The normal approach to a solution is to use javascript window.open(...), but that will inihibit the standard postback.
Another approach i have seen, was to set the Page.Form.Target to "_blank" which does cause postback as well as opening a new page with the result. But this alone leaves the original page to keep targeting new pages forever - at least until its refreshed. Since it makes new pages on every form postback, it is not refreshed unless the user does it manually.
Some suggest at you wrap a form around the button, but some coding environments, like ASP.NET, really don't like that.
The solution
This seems to be to set the forms target to _blank, and then make the Page.Form.Target to be restored somehow. I suggest to use the window.setTimeout() to do this.
Button1.Attributes.Add(
"onclick",
"JavaScript:document.getElementById('" + Page.Form.ClientID + "').target = '_blank'; " +
"window.setTimeout(\"document.getElementById('" + Page.Form.ClientID + "').target = '_self';\",250);"
);
In the example, making an export button, I am creating some Excel output in the codebehind. The first part of the script, causes the forms target to create a new window, before posting, and it ensures that the server output is directed to the new window.
It's also possible to reload the page by JS, just like restoring Form.Target, but this requires an extra server request. Reloading the original page may be needed in special cases or environments. For most ASP.NET solution, the shown restore method is excellent.
The code uses the setTimeout() method to set up a restore script, that fires after 250ms. This is needed because ASP.NET adds some postback code, out of your control, after your own JS code. The script attached to the button onclick by .NET, will eventually cause a postback.
Instead of trying to simulate the ASP.NET submit with the chance of breaking the structure with new ASP.NET versions, the example allows the ASP.NET code to complete, and after 250ms restore the forms target.
Voila, just one line of code (shown with wrapping here tomake it readable) to make new windows, make submit, and restore page functions. You should wrap the thing in a new UserControl, maybe called ButtonNewWindow.
This method has some very important advantages over other methods.
- It's completely independent from ASP.NET behavior.
- It can basically be used with any technology
- It can be implemented into any site as is
The code example is made in C#.NET, but the method can be implemented in any environment and in any language.