单击时下载PDF(不在浏览器中打开)

时间:2014-10-12 10:08:55

标签: c# asp.net pdf

我有一个PDF文件的href链接,当点击它时会在浏览器的新页面中打开。我想要下载而不是在新标签页中打开。

那么如何使PDF文件链接可以下载而不是在浏览器中打开呢?

以下是代码:

<asp:FormView ID="FormView2" runat="server">
            <ItemTemplate>
                <asp:LoginView ID="LoginView1" runat="server">
                    <LoggedInTemplate>
                          <asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank"></asp:HyperLink>
                        <br />
                    </LoggedInTemplate>
                    <AnonymousTemplate>
                            <p>You need to log in to view the book.</p>
                    </AnonymousTemplate>
                </asp:LoginView>
            </ItemTemplate>
        </asp:FormView>

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    int bookId = Convert.ToInt32(Request.QueryString.Get("BookId"));


    using (LibraryEntities entities = new LibraryEntities())
    {
        var book = (from r in entities.Books
                          where r.Id == bookId
                          select r);
        FormView2.DataSource = book;
        FormView2.DataBind();
    }
}

2 个答案:

答案 0 :(得分:2)

只需将属性download添加到<asp:HyperLink>

最终代码将是。

<asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" 
               NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank" download
</asp:HyperLink>

注意:这是HTML5属性,因此仅适用于HTML5兼容的浏览器。请查看此链接,以查看不同浏览器上的download属性支持 - http://caniuse.com/#feat=download

答案 1 :(得分:0)

Response.Clear(); //eliminates issues where some response has already been sent
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.sql", filename));
Response.Write(yourSQL);
Response.End();

类似问题已被问及here

相关问题