简体   繁体   English

使用 gridview 中的链接从 web 页面打开本地文件 c#

[英]Open local file from a web page using link in gridview c#

I need to open a some types of files like.jpg, word, .pdf when the user clicks on link in gridview. Right now i am using this code and its not opening up.当用户单击 gridview 中的链接时,我需要打开一些类型的文件,如 .jpg、word、.pdf。现在我正在使用这段代码,但它没有打开。

It is a web application and i have to open the file which is present in the local drive of user.这是一个 web 应用程序,我必须打开用户本地驱动器中存在的文件。 I would be binding the path of file in NavigateUrl property of the hyperlink我将在超链接的 NavigateUrl 属性中绑定文件路径

<asp:hyperlink ID="HyplnkName" runat="server" NavigateUrl= '<%# ConfigurationManager.AppSettings["ImagesFilePath"]) %>' Target="_top" Text='<%# DataBinder.Eval(Container, "DataItem.FileName") %>' />

Here is what i used in my project这是我在我的项目中使用的

<asp:HyperLink ID="hlPdf" runat="server" NavigateUrl="~/PdfHandler.ashx" Target="_blank">Click to view PDF</asp:HyperLink>

This is ashx handler file这是 ashx 处理程序文件

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

public class PdfHandler : IHttpHandler 
{

  public void ProcessRequest (HttpContext context) 
  {
    byte[] data = File.ReadAllBytes(@"Your Path");
    context.Response.ContentType = "application/pdf";
    context.Response.OutputStream.Write(data, 0, data.Length);
  }

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

use OnRowDataBound instead:使用 OnRowDataBound 代替:

aspx page: aspx 页面:

<asp:GridView ID="GridView1" runat="server" 
    onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
    <asp:HyperLink ID="HL" runat="server" Target ="_blank"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

code behind:背后的代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink hlink = (HyperLink)e.Row.FindControl("HL");
        string url = "~/Docs/" + e.Row.Cells[1].Text;
        hlink.NavigateUrl = url;
        hlink.Text = "Read";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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