Response.Redirect到新窗口

时间:2020-03-06 14:27:24  来源:igfitidea点击:

我想做一个Response.Redirect(" MyPage.aspx"),但是要在新的浏览器窗口中打开它。我之前没有使用JavaScript注册脚本方法就已经这样做了。我只是不记得怎么了?

解决方案

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

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

如果我们可以直接写入Response流,则可以尝试以下操作:

response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");

我们可能需要使用Page.RegisterStartupScript来确保JavaScript在页面加载时触发。

我刚刚找到了答案,它可以工作:)

我们需要将以下内容添加到服务器端链接/按钮:

OnClientClick="aspnetForm.target ='_blank';"

我的整个按钮代码如下所示:

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" 
                OnClick="myButton_Click" 
                OnClientClick="aspnetForm.target ='_blank';"/>

在服务器端的OnClick上,我执行Response.Redirect(" MyPage.aspx");,然后在新窗口中打开页面。

我们需要添加的另一部分是修复表单的目标,否则每个链接都将在新窗口中打开。为此,在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>

<body onload="fixform()">

我们也可以像这样在后面的代码中使用

ClientScript.RegisterStartupScript(this.Page.GetType(), "",
  "window.open('page.aspx','Graph','height=400,width=500');", true);

fixform技巧很巧妙,但是:

  • 我们可能无权访问新窗口中加载的代码。
  • 即使我们这样做,也要依靠它始终加载,无错误的事实。
  • 并且我们依赖于这样的事实,即用户不会在另一个页面有机会加载和运行fixform之前单击另一个按钮。

我建议这样做:

OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"

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

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

我总是使用此代码...
使用此代码

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

我们可以像我在这里一样使用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);
}