2012-01-29 137 views
12

如何在C#ASP.NET中的按鈕單擊事件上打開新的瀏覽器窗口?如何在按鈕點擊事件中打開新的瀏覽器窗口?

請分享任何示例。

我正在做下面的代碼。請讓我知道我出錯的地方。

btn_Click() 
{ 
    if(condition==true) 
    { 
     this.Page.ClientScript.RegisterStartupScript(
      this.GetType(), 
      "page_index_script2", 
      "openNewWindow();", 
      true 
     ); 
    } 
} 

以及JavaScript函數是

function openNewWindow() 
{ 
    alert('HI'); 
    window.open('http://www.stackoverflow.com'); 
} 

當我從javascript函數警報工程運行的代碼,但沒有得到開闢了新的窗口。

+0

你想打開的新窗口在處理後面的代碼事件之前,或只是在新窗口中的某個鏈接? – ivowiblo 2012-01-29 19:43:25

+1

請勿將「C#ASP.NET」等內容添加到標題的末尾。這就是標籤的用途。 – 2012-01-29 20:27:34

回答

16

你可以使用一些這樣的代碼,你可以調整高度和寬度根據自己的需要

protected void button_Click(object sender, EventArgs e) 
    { 
     // open a pop up window at the center of the page. 
     ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open('your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'');", true); 
    } 
+0

如何防止在導航回頁面時運行此彈出腳本? – 2016-08-09 18:38:48

+0

@JamesWierzba你不能檢查網址引用或什麼?我認爲這應該工作。 – DotNetUser 2016-08-30 17:33:32

2

的Response.Write( '...的JavaScript打開一個窗口...')

http://www.aspspider.com/qa/Question2714.aspx

+2

注意:這樣的代碼會在瀏覽器中對「彈出窗口阻止程序」進行檢查,通常會導致無操作(當它被回答時可能會返回2008年)。 – 2012-01-29 23:18:01

+0

是的,當然,在處理彈出窗口時,我們必須時常擔心實際瀏覽器的功能。 – Kristian 2012-01-30 06:44:32

+0

答案中的鏈接中斷 – ihimv 2015-11-10 10:42:40

10

它可以通過OnClientClick[MSDN]事件中完成所有的客戶端處理器和window.open[MDN]

<asp:Button 
    runat="server" 
    OnClientClick="window.open('http://www.stackoverflow.com'); return false;"> 
    Open a new window! 
</asp:Button> 
+0

我嘗試了所有後端模式,但這是最簡單的。在Code-Behind中,我會執行必要的檢查並構建URL,然後以此方式將其掛接到OnClientClick上 - btnButton.OnClientClick =「window.open('」+ customURL +''); return false;「 ;這適用於Button和LinkBut​​tons(在我的情況下)。 – SollyM 2015-07-01 14:47:56

+0

這很完美。 – 2017-02-20 21:56:25

2

或寫入響應流:

Response.Write("<script>"); 
Response.Write("window.open('page.html','_blank')"); 
Response.Write("</script>"); 
相關問題