简体   繁体   中英

How to open a new window from only one asp.net control

I have the following codes which opens a PDF file in a new window from the current page:

<asp:LinkButton ID="lnkView2" Text="View in Browser" OnClientClick="window.document.forms[0].target='_blank';" runat="server" OnClick="ViewFile" />

protected void ViewFile(object sender, EventArgs e)
{
    strFileName = "APP_" + k.Trim(' ') + "_" + c.Trim(' ') + "_NoID.pdf";
    Session["fileName"] = strFileName;
    Response.Redirect("OpenFilePDF.ashx?fileVar=" + Session["fileName"]);
}

OpenFilePDF.ashx which is using the folder created in the website server:

<%@ WebHandler Language="C#" Class="OpenFilePDF" %>

using System;
using System.Web;
using System.IO;

public class OpenFilePDF : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
        string strSessVar2 = request2.QueryString["fileVar"];

        try
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "application/pdf";
            byte[] fileByteArray = File.ReadAllBytes(Path.Combine(@"C:\PDFGenerate", strSessVar2));
            response.AddHeader("Content-disposition", String.Format("inline; filename={0}", strSessVar2));
            response.BinaryWrite(fileByteArray);
            response.End();
        }
        catch (Exception ce)
        {

        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

What is happening is when I click on the LinkButton it opens a new window from the current page, and everything is good.

But lets say I click on the following button (or any links) on the current page:

<asp:Button ID="btnGeneratePDF" ClientIDMode="Static" runat="server" Text="Generate PDF" CommandArgument='#SOMETHING GOES HERE' />

It keeps opening new window each time which I want to prevent. The only way it doesn't open new window, is if I don't open a new page and redirect on the same page and user comes back to the current page it doesn't open a new window each time.

How do I modify the code so that only LinkButton control will open a new window and any other controls will open on the same page and not in the new window?

AFAIK, there is no built-in way to specify "new tab or window, but only once". In pure HTML, the attribute that handles this is:

<a href="yourURL" target="_blank">Some Link</a>

And every time you click on that element, a new tab or window will appear (but only for that link). What is happening in your case, however, is that .NET is outputting for you something like:

<a href="yourURL" onclick="window.document.forms[0].target='_blank';">Some Link</a>

Though they may at first seem similar, they are not. When the click happens, your code will transform your page which initially looks like:

<!-- this is the ASP.NET form that handles all postbacks for all controls -->
<form> 
...
</form>

Into

<form target="_blank">
<!-- well now you're screwed -->
...
</form>

Thankfully, the fix is simple.

ASPX:

<a ID="lnkView2" runat="Server" target="_blank">some text</a>

Code behind:

protected void Page_Load(...
{
   ...
   strFileName = "APP_" + k.Trim(' ') + "_" + c.Trim(' ') + "_NoID.pdf";
   Session["fileName"] = strFileName;
   lnkView2.HRef = OpenFilePDF.ashx?fileVar=" + Session["fileName"];
}

One additional advantageous reason this is good is that you are reducing a round-trip to your server for the browser. The way you have it now, it goes page->postback redirect->ashx whereas directly linking will fix your issue with other controls and turn the path into page->ashx cutting out one unnecessary step.

Here's a much simpler workaround, but keep in mind that following this path is a form of technical debt. You are introducing a potential future bug to fix a current one, but it involves fewer code changes on your end in the short-term.

Revert any changes from my previous answer, add this to the top of your ASPX page:

<script type="text/javascript">
    var retargetFunc = function() {
        window.document.forms[0].target='_self';
    }

    var ele = window.document.forms[0];
    if(ele.addEventListener){
        ele.addEventListener("submit", retargetFunc , false);
    }else if(ele.attachEvent){
        ele.attachEvent('onsubmit', retargetFunc );
    }
</script>

What will this do? Once you submit your form, it will change the target="_blank" back to the default behavior of target="_self" , so any further control clicks aside from the link button will post the current window. However, because the link button still sets the target on click, only clicks on the link button itself will go to another tab.

All things being equal, I'd prefer it if you used my earlier solution but this dirty answer will probably work for you and is much easier to implement.

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