C# Response.Redirect 到新窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/104601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:08:52  来源:igfitidea点击:

Response.Redirect to new window

提问by

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?

我想做一个Response.Redirect("MyPage.aspx")但在新的浏览器窗口中打开它。我以前在没有使用 JavaScript 注册脚本方法的情况下这样做过。我就是想不起来怎么办?

回答by John Sheehan

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?

这对于 Response.Redirect 是不可能的,因为它发生在服务器端并且无法指示您的浏览器执行该操作。初始窗口中会留下什么?空白页?

回答by JamesSugrue

Because Response.Redirect is initiated on the server you can't do it using that.

因为 Response.Redirect 是在服务器上启动的,所以你不能使用它来做。

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

回答by CodeRot

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

您可能希望使用 Page.RegisterStartupScript 来确保 javascript 在页面加载时触发。

回答by CodeRot

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.

在服务器端 OnClick 我做了一个Response.Redirect("MyPage.aspx");页面在新窗口中打开。

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.

您需要添加的另一部分是修复表单的目标,否则每个链接都会在新窗口中打开。为此,请在 POPUP 窗口的标题中添加以下内容。

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

回答by CodeRot

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

回答by tom

The fixform trick is neat, but:

fixform 技巧很巧妙,但是:

  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.

  1. 您可能无法访问新窗口中加载的代码。

  2. 即使你这样做,你也依赖于它总是加载的事实,没有错误。

  3. 而且您依赖于这样一个事实,即在另一个页面有机会加载和运行 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:

并在同一页面上设置 fixform ,如下所示:

function fixform() {
   document.getElementById("aspnetForm").target = '';
}

回答by Abhishek Shrivastava

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

回答by Yaplex

you can open new window from asp.net code behindusing ajax like I did here http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/

您可以像我在这里所做的那样使用 ajax 从后面的 asp.net 代码打开新窗口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);
}

回答by Sasa Tancev

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 对象

Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10");

回答by dpp

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

来源:http: //dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/