How to open new browser window on button click event in C# ASP.NET?
Please share any example.
I am doing following code. Please let me know where I am going wrong.
btn_Click()
{
if(condition==true)
{
this.Page.ClientScript.RegisterStartupScript(
this.GetType(),
"page_index_script2",
"openNewWindow();",
true
);
}
}
And the JavaScript function is
function openNewWindow()
{
alert('HI');
window.open('http://www.stackoverflow.com');
}
When I run the code from javascript function Alert works but new window is not getting opened.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use some code like this, you can adjust a height and width as per your need
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);
}
Method 2
It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:
<asp:Button
runat="server"
OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
Open a new window!
</asp:Button>
Method 3
Response.Write(‘… javascript that opens a window…’)
http://www.aspspider.com/qa/Question2714.aspx
Method 4
Or write to the response stream:
Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0