相对于客户端的URL HTTP URL [英] relative client url to http url

查看:166
本文介绍了相对于客户端的URL HTTP URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 〜/ _docs /文件夹/文件夹/ document.pdf

我怎么能,在视图中,将其转换为一个链接下载文件本身?

感谢


解决方案

 < A HREF =<%= Url.Content(〜/ _docs /文件夹/文件夹/文件.PDF)%>>
    document.pdf
&所述; / A>

或者使这更优雅,更避免了意大利面条code,你可以写一个自定义的HTML帮助:

 公共静态类HtmlExtensions
{
    公共静态MvcHtmlString ContentLink(
        这个的HtmlHelper的HtmlHelper,
        串LINKTEXT,
        字符串的contentPath,
        对象htmlAttributes
    )
    {
        变种一个=新TagBuilder(一);
        VAR urlHelper =新UrlHelper(htmlHelper.ViewContext.RequestContext,htmlHelper.RouteCollection);
        a.MergeAttribute(的href,urlHelper.Content(的contentPath));
        a.MergeAttributes(新RouteValueDictionary(htmlAttributes));
        a.SetInnerText(LINKTEXT);
        返回MvcHtmlString.Create(a.ToString());
    }
}

和则:

 <%= Html.ContentLink(
    download.pdf
    〜/ _docs /文件夹/文件夹/ document.pdf
    新{title =下载download.pdf}
)%GT;

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

解决方案

<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" }
) %>

这篇关于相对于客户端的URL HTTP URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆