天天看點

[轉貼]Response.Redirect 打開新視窗的兩種方法

一般情況下,response.redirect 方法是在伺服器端進行轉向,是以,除非使用 response.write("<script>window.location='http://dotnet.aspx.cc';</script>") 方法外,是不能在新視窗打開所指定的  url 位址的。但是,如果仔細分析一下,如果設定 form 元素的 target 屬性,還是有辦法打開新視窗的。下面就是可以采用的兩種方法。

方法一:在伺服器端設定 target 屬性,這個方法也非常适用于用戶端不支援腳本的情況。代碼如下:

<%@ page language="c#" autoeventwireup="true" %>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"

 "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<script runat="server">

    protected void page_load(object sender, eventargs e)

    {

        form1.target = "_blank";

    }

    protected void button1_click(object sender, eventargs e)

        response.redirect("http://dotnet.aspx.cc");

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="head1" runat="server">

    <title></title>

</head>

<body id="b" runat="server">

<form id="form1" runat="server">

    <asp:button id="button1" runat="server" onclick="button1_click" text="打開新視窗或者新 tab " />

</form>

</body>

</html>

辦法二:采用用戶端腳本的方法設定 target 屬性。代碼如下:

        button1.attributes.add("onclick", "this.form.target='_newname'");

上面兩種方法中的 target 屬性可以采用任何合法的名稱,但要注意,如果相同名稱的視窗已經打開,則新視窗會在已經存在名稱的視窗裡打開。

更新:如果需要設定彈出視窗的寬度和高度,可以修改為下面的方法:

      string windowname = "win" + system.datetime.now.ticks.tostring();

      page.registeronsubmitstatement("js", "window.open('','" + windowname + "','width=600,height=200')");

        form1.target = windowname;

另外一種彈出的方法可以參見老外的文章:

http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx

繼續閱讀