[c#] Response.Redirect to new window

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?

This question is related to c# asp.net response.redirect

The answer is


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>

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?


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

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

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.


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.


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

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)

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

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

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

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

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


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

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.


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

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

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


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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to response.redirect

Redirecting new tab on button click.(Response.Redirect) in asp.net C# go to link on button click - jquery Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()? Response.Redirect to new window Response.Redirect with POST instead of Get?