relative client url to http url

你离开我真会死。 提交于 2019-12-13 04:45:43

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/3816836/relative-client-url-to-http-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!