asp:Hyperlink in Gridview open PDF in new browser window

纵饮孤独 提交于 2019-12-25 00:12:35

问题


I currently have a gridview that dynamically creates asp:Hyperlinks to PDF files. Right now, the url just downloads the file to the local machine. What's the easiest way to get them to open in a new window so the user has the option to print or download. Chrome automatically downloads it. IE asks to open or save it. I just want it to open in a browser window.

<asp:TemplateField HeaderText="Name">
    <ItemTemplate>
        <asp:HyperLink ID="lblProductName" runat="server" Text='<%# Eval("name") %>' NavigateUrl="#" Target="_blank"  ></asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

And the actual NavigateUrl gets created in the code behind

HyperLink lblProductName = (HyperLink)e.Row.FindControl("lblProductName");
lblProductName.NavigateUrl = urlLink;

回答1:


Add a new page say DownloadFile.aspx and add the following code

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
    string fileName = Request.QueryString["pdffile"];
    string path = Server.MapPath("~/PDFs/") + fileName;
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.WriteFile(path);
    Response.Flush();
    Response.End();
}
}

Now in GridView remove LinkButton and add HyperLink as shown below

<asp:HyperLink ID="HyperLink1" runat="server" Target = "_Blank" NavigateUrl='<%# Eval("FileName","DownloadFile.aspx?PDFFile={0}") %>'></asp:HyperLink>


来源:https://stackoverflow.com/questions/44652249/asphyperlink-in-gridview-open-pdf-in-new-browser-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!