Response.Redirect to new window

C#asp.netresponse.redirect

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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()">

Solution 2 - C#

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");

Solution 3 - C#

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);

Solution 4 - C#

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>");

Solution 5 - C#

The fixform trick is neat, but:

  1. You may not have access to the code of what loads in the new window.

  2. Even if you do, you are depending on the fact that it always loads, error free.

  3. 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 = '';
}

Solution 6 - C#

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);

Solution 7 - C#

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?

Solution 8 - C#

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();"/>

Solution 9 - C#

<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/

Solution 10 - C#

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;";
}

Solution 11 - C#

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.

Solution 12 - C#

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 ());
     }

Solution 13 - C#

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','');
}

Solution 14 - C#

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>

Solution 15 - C#

You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.

Solution 16 - C#

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);
}

Solution 17 - C#

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.

Solution 18 - C#

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.

Solution 19 - C#

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)

Solution 20 - C#

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); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFouadView Question on Stackoverflow
Solution 1 - C#FouadView Answer on Stackoverflow
Solution 2 - C#Sasa TancevView Answer on Stackoverflow
Solution 3 - C#steveView Answer on Stackoverflow
Solution 4 - C#JamesSugrueView Answer on Stackoverflow
Solution 5 - C#tomView Answer on Stackoverflow
Solution 6 - C#shaluView Answer on Stackoverflow
Solution 7 - C#John SheehanView Answer on Stackoverflow
Solution 8 - C#Zen Of KursatView Answer on Stackoverflow
Solution 9 - C#dppView Answer on Stackoverflow
Solution 10 - C#humbadsView Answer on Stackoverflow
Solution 11 - C#ZohaibView Answer on Stackoverflow
Solution 12 - C#Abhishek ShrivastavaView Answer on Stackoverflow
Solution 13 - C#Ben BarrethView Answer on Stackoverflow
Solution 14 - C#bokkieView Answer on Stackoverflow
Solution 15 - C#CodeRotView Answer on Stackoverflow
Solution 16 - C#YaplexView Answer on Stackoverflow
Solution 17 - C#crh225View Answer on Stackoverflow
Solution 18 - C#RickettsView Answer on Stackoverflow
Solution 19 - C#HevskiView Answer on Stackoverflow
Solution 20 - C#Tran Anh HienView Answer on Stackoverflow