相对客户端 url 到 http url

发布于 2024-09-25 23:03:22 字数 137 浏览 0 评论 0原文

我有一个模型类的属性,其中包含文件的相对 URL。

~/_docs/folder/folder/document.pdf

在视图中,我如何将其转换为超链接以下载文件本身?

谢谢

I have a property of a model class that contains a relative url to a file.

~/_docs/folder/folder/document.pdf

How I can, in the view, transform it to an hyperlink to download the file itself?

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所谓喜欢 2024-10-02 23:03:22
<a href="<%= Url.Content("~/_docs/folder/folder/document.pdf") %>">
    document.pdf
</a>

或者为了使其更优雅并避免意大利面条式代码,您可以编写一个自定义 html 帮助器:

public static class HtmlExtensions
{
    public static MvcHtmlString ContentLink(
        this HtmlHelper htmlHelper, 
        string linkText, 
        string contentPath, 
        object htmlAttributes
    )
    {
        var a = new TagBuilder("a");
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
        a.MergeAttribute("href", urlHelper.Content(contentPath));
        a.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        a.SetInnerText(linkText);
        return MvcHtmlString.Create(a.ToString());
    }
}

然后:

<%= Html.ContentLink(
    "download.pdf", 
    "~/_docs/folder/folder/document.pdf", 
    new { title = "Download download.pdf" }
) %>
<a href="<%= Url.Content("~/_docs/folder/folder/document.pdf") %>">
    document.pdf
</a>

Or to make this more elegant and avoid the spaghetti code you could write a custom html helper:

public static class HtmlExtensions
{
    public static MvcHtmlString ContentLink(
        this HtmlHelper htmlHelper, 
        string linkText, 
        string contentPath, 
        object htmlAttributes
    )
    {
        var a = new TagBuilder("a");
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
        a.MergeAttribute("href", urlHelper.Content(contentPath));
        a.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        a.SetInnerText(linkText);
        return MvcHtmlString.Create(a.ToString());
    }
}

and then:

<%= Html.ContentLink(
    "download.pdf", 
    "~/_docs/folder/folder/document.pdf", 
    new { title = "Download download.pdf" }
) %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文