使用按钮在ASP.NET中的新选项卡/窗口中打开链接

时间:2012-05-10 15:54:43

标签: asp.net

我正在尝试使用按钮单击在新标签/窗口中打开页面。我查看了类似于this的解决方案,但是那里给出的答案要么是使用链接,要么在同一个窗口中打开它。我需要使用一个按钮,因为它需要根据表单中输入的条件数据生成链接(字符串操作)。此按钮不提交表格;它只是验证外部网站上的一些数据。我需要在不同的窗口或标签中使用它,以便它们可以在我的表单和验证站点之间来回切换。这基本上是我当前的Button_Click事件:

var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "&param1=foo&param2=bar";
Response.Redirect(Url);

除了Response.Redirect(Url)仅在同一窗口中打开,而不是新窗口之外,这是有效的。

2 个答案:

答案 0 :(得分:6)

只需从Button上的Click事件处理程序中吐出javascript代码。

var Address = AddressTextbox.Text.Trim();
Address = Address.Replace(' ', '+');
var Url = "http://www.example.com/query?text=" + Address + "&param1=foo&param2=bar";
Page.ClientScript.RegisterStartupScript(this.GetType(), "dsadas", "window.open('"+Url+"');", true);

答案 1 :(得分:3)

使用OnClientClick属性:

<script type="text/javascript">
    redirectToPage = function(url){
        void(window.open(url, "child_window"));
        return false;
    }
</script>
<asp:Button ID="Button1" runat="server"
    Text="Click Me!"
    OnClientClick="return redirectToPage('/somefolder/somepage.aspx');" />

使用OnClientClick属性,最后记住return false非常重要,否则按钮点击会触发回发。

修改

如果要从click事件处理程序中打开一个新窗口,可以执行以下操作:

protected void Button1_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "open_window", 
        string.Format("void(window.open('{0}', 'child_window'));", "/somefolder/somepage.aspx"), true);
}

不可否认,这有点难看,但是如果在执行按钮点击逻辑之前有某些信息是你没有的,那么这可能是你最好的选择。如果您有任何方法可以在单击按钮之前构建URL,则可以在代码隐藏中分配OnClientClick