简体   繁体   中英

Open Window in new tab using an ASP.NET Button, C#, and the code behind the page

I am working on a website that produces internal reports and I have been tasked with opening those reports in a new tab/window with the restriction that any scripts must be run from the code behind and not written in the html/aspx portion of the website.

my current attempt at testing the code is this:

 protected void Button2_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('http://www.google.com','_newtab');", true);
    }

The Button code is:

     <td>
          <asp:Button ID="Button2" runat="server" Text="Search" Width="83px" OnClick="Button2_Click" />
     </td>

This is a direct grab from the example project that shows how to do this. the problem is that nothing happens. it's as if the code is getting skipped over by Visual Studio. I have also checked that all of the same items are in the "Using" section at the top of the code. do i need to have a script manager or something? does anyone have suggestions on what i may be overlooking?

Seems you are trying to open new window on button click but _newtab which is not valid.

You should try this way:

Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('http://www.microsoft.com', '_blank');", true);

Update:

Your .CS File

protected void ButtonClick(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('http://www.microsoft.com', '_blank');", true);

    }

Your Aspx File

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebFormTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

         <asp:Button Text="Open New Window" OnClick="ButtonClick"  type="button" runat="server" />

        </div>


    </form>

</body>
</html>

Hope it would help what you are trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM