I want to do a Response.Redirect("MyPage.aspx")
but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?

- 31,810
- 31
- 111
- 133
21 Answers
I just found the answer and it works :)
You need to add the following to your server side link/button:
OnClientClick="aspnetForm.target ='_blank';"
My entire button code looks something like:
<asp:LinkButton ID="myButton" runat="server" Text="Click Me!"
OnClick="myButton_Click"
OnClientClick="aspnetForm.target ='_blank';"/>
In the server side OnClick I do a Response.Redirect("MyPage.aspx");
and the page is opened in a new window.
The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
and
<body onload="fixform()">

- 73
- 1
- 2
- 7
-
2Nope as this uses javascript to change the target of the form. Instead the page would submit as normal. – Toby Mills Sep 19 '08 at 21:44
-
Plus you could have a security violation if you want to redirect to a page outside your virtual directory. – Drejc Sep 22 '08 at 21:42
-
1Somehow in my case its not working. I'm opening the same page in the new window and writing the response to that page. But when I keep fixform() method in the masterpage it throws error saying document is null. Not sure why it is throwing still trying to find a solution. Though I've come up with a temporary solution by using onClientClick="aspnetForm.target='';" property for other buttons on that page. – JPReddy Jun 25 '10 at 10:42
-
1I've just tried this and instead of `OnClientClick="aspnetForm.target ='_blank';"` I had to use `OnClientClick="document.getElementById('Form').target ='_blank';"` – colincameron Nov 14 '12 at 11:03
-
Yes, it did work for me but it is opening the page into new tab not in a new window. How can I open my page in a new window? – Shilpa Soni Sep 03 '14 at 06:48
-
@ShilpaSoni that depends on browser settings, there's nothing you can do in code to force a new window instead of a new tab short of using a modal or a message box AFAIK. – eddie_cat Nov 26 '14 at 15:31
-
My form name was not aspnetForm, so I needed to check in Google Chrome Dev Tools the id of my form, then I changed like this : `OnClientClick="myform.target ='_blank';"` – Guilherme de Jesus Santos Jun 04 '18 at 12:40
-
You can get rid of the "fixform" part simply by defining your form with target = "_self", so the target = "_blank" will override just the current page ` – Stefano Losi Feb 16 '19 at 10:11
-
In my aspnetForm, there are two link buttons. It works perfectly for the first attempt. For example, If I click on any of the buttons for the first time the Response.Redirect open in a new window. But I click on the same button a second time or I click on another button it is not working. Is there a way the functionality should work each and every time while clicking on any button? Thanks – thedeepponkiya Jun 12 '23 at 11:53
You can use this as extension method
public static class ResponseHelper
{
public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;
if (page == null)
{
throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = @"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else
{
script = @"window.open(""{0}"", ""{1}"");";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
}
}
}
With this you get nice override on the actual Response object
Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10");

- 645
- 5
- 5
-
1
-
1Excellent reusable solution! The only downside is the fact the new window is blocked by the popup blocker. – MeanGreen Jun 12 '15 at 07:49
-
-
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);

- 1,786
- 1
- 15
- 29
-
-
4window.open in this example will always be treated as a'popup' since it is initiated by code and not a user action. if window.open is called when the user clicks on an element, that should sidestep the blocked popup action by the browser. – steve Nov 27 '13 at 18:50
-
@steve, This an excellent and very simple solution. I used your approach to Response.Redirect to a popup. – Sunil Apr 30 '14 at 20:29
Because Response.Redirect is initiated on the server you can't do it using that.
If you can write directly to the Response stream you could try something like:
response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");

- 14,891
- 10
- 61
- 93
-
3This work, but then the page where my button is get's changes, its like the CSS or DIVS are being affected. – Etienne Oct 21 '09 at 09:02
-
The fixform trick is neat, but:
You may not have access to the code of what loads in the new window.
Even if you do, you are depending on the fact that it always loads, error free.
And you are depending on the fact that the user won't click another button before the other page gets a chance to load and run fixform.
I would suggest doing this instead:
OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"
And set up fixform on the same page, looking like this:
function fixform() {
document.getElementById("aspnetForm").target = '';
}
You can also use in code behind like this way
ClientScript.RegisterStartupScript(this.Page.GetType(), "",
"window.open('page.aspx','Graph','height=400,width=500');", true);

- 222,467
- 53
- 283
- 367
-
2This works fine for me and is basically the short version of Abhishek Shrivastava's solution above. However, there are a couple of caveats to be aware of. First, this will trigger popup blockers. In particular, it will not work at all in Safari 5.0 if the popup blocker is enabled as Safari doesn't prompt you for blocked popups and doesn't allow you to make popup exceptions. Second, Chrome ignores the page argument to window.open. So even if you use `window.open('page.aspx','_blank');` it still opens it in a new window with navigation bar disabled and nav buttons missing instead of a new tab. – Kasey Speakman Jun 14 '11 at 22:30
This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?

- 77,456
- 30
- 160
- 194
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>

- 2,672
- 1
- 31
- 47
-
I cant edit yout post as is not 6 characters at least, but it is not '("href")', It is '["href"]' – Nickso Mar 07 '19 at 17:17
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"
OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/

- 28,987
- 33
- 107
- 157
You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.

- 109
- 5
-
This method triggers the both _OnClientClick_ as well as _onclick_. Meant some page is opened in the new window as well as some action was done in the same page – Manivannan Nagarajan Feb 24 '14 at 09:11
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}

- 3,252
- 1
- 27
- 22
I always use this code... Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}

- 749
- 6
- 14
-
This code will never affect the CSS class so the parent window will not be affected at all!! – Abhishek Shrivastava Aug 26 '10 at 18:19
-
1Well, this certainly is a strong argument for MVC. Not to take anything away from your code. Far from it. It's things like this that typify webforms, blech. – MrBoJangles Dec 28 '10 at 22:19
-
All of this code can be condensed to one line... see shalu's solution below. It's exactly the same effect, but without all the unneeded bloat. – Kasey Speakman Jun 14 '11 at 22:33
Here's a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:
<asp:Button ID="btnSubmit" OnClientClick="openNewWin();" Text="Submit" OnClick="btn_OnClick" runat="server"/>
Then in your js file referenced on the SAME page:
function openNewWin () {
$('form').attr('target','_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget(){
$('form').attr('target','');
}

- 1,675
- 1
- 15
- 16
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink>

- 1,477
- 4
- 21
- 40
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.

- 893
- 6
- 12
None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.
Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = "window.open('" + URL + "'); return false;"
I was having to modify someone else's response.redirect code to open in a new browser.

- 821
- 18
- 34
I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.
$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
$(".new-window").on("click", function () {
//--- change the form's target
$("#aspnetForm").prop("target", "_blank");
//--- change the target back after the window has opened
setTimeout(function () {
$("#aspnetForm").prop("target", "");
}, 1);
});
});
To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.

- 5,025
- 4
- 35
- 48
I did this by putting target="_blank" in the linkbutton
<asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" />
then in the codebehind pageload just set the href attribute:
btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)

- 1,821
- 1
- 17
- 26
you can open new window from asp.net code behind using ajax like I did here http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectionChanged += CalendarSelectionChanged;
}
private void CalendarSelectionChanged(object sender, EventArgs e)
{
DateTime selectedDate = ((Calendar) sender).SelectedDate;
string url = "HistoryRates.aspx?date="
+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"rates" + selectedDate, "openWindow('" + url + "');", true);
}

- 2,272
- 1
- 20
- 38
HTML
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />
Javascript:
function SetTarget() {
document.forms[0].target = "_blank";}
AND codebehind:
Response.Redirect(URL);

- 687
- 8
- 11
This approach is simple and works fine:
string script = "window.open('" + yourUrl + "', '_blank');";
ScriptManager.RegisterStartupScript(this, GetType(), "OpenNewWindow", script, true);

- 454
- 2
- 6
- 15