【问题标题】:Open file from table dynamicaly with razor用剃刀从表中动态打开文件
【发布时间】:2013-05-16 08:27:20
【问题描述】:

您好,我正在使用 razor 显示 Table,其中包含带有一些不同细节的文件列表。当我点击他的名字时,我只想显示一个文件。

这是我的看法:

<table>
<tr>
    <th>
        Nom
    </th>
    <th>
        Date
    </th>
    <th>
        Uploader
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
          <a href = @Url.Action("ViewAttachment", new { fileName = item.Path }) > @Html.DisplayFor(modelItem => item.Nom) </a>  


    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Uploader)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.DocumentID }) |
        @Html.ActionLink("Details", "Details", new { id=item.DocumentID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.DocumentID })
    </td>
</tr>
}

</table>

在我的操作中,我将文件的路径发送到控制器。但我不知道如何处理它。

public ActionResult ViewAttachment(string fileName)
    {
        try
        {
            return Redirect(filename);
        }
        catch
        {
            throw new HttpException(404, "Couldn't find " + fileName);
        }


    } 

当我点击它时将我重定向到domain/Document/Content/myfile,但我的文件在domain/Content/myfile

【问题讨论】:

    标签: asp.net asp.net-mvc-3 razor


    【解决方案1】:

    当我点击他的名字时如何打开文件?

    如果文件位于服务器上可由客户端直接访问的位置,则您不需要控制器操作,您可以直接将链接指向该位置:

    <a href="@Url.Content("~/content/" + System.IO.Path.GetFileName(item.Path))"> 
        @Html.DisplayFor(modelItem => item.Nom) 
    </a>  
    

    如果客户端无法访问该文件,那么您需要一个控制器操作通过返回 File 结果来提供该文件:

    public ActionResult ViewAttachment(string fileName)
    {
        fileName = System.IO.Path.GetFileName(fileName);
        string file = Server.MapPath("~/Content/" + fileName);
        if (!File.Exists(file))
        {
            return HttpNotFound();
        }  
        return File(file, fileName, "application/octet-stream");
    }
    

    如果您想在新选项卡中打开目标文件,您可以将 target="_blank" 属性添加到锚点:

    <a href="@Url.Content("~/content/" + System.IO.Path.GetFileName(item.Path))" target="_blank"> 
        @Html.DisplayFor(modelItem => item.Nom) 
    </a>  
    

    【讨论】:

    • 您的解决方案效果很好,但您可以编辑响应以显示如何在新选项卡中打开目标文件吗?
    • 您可以将target="_blank" 属性添加到锚点。我已更新我的答案以包含此信息。
    猜你喜欢
    • 2020-12-02
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多