2010-09-28 68 views
0

我有一個模型類的屬性,它包含一個文件的相對URL。相對客戶端URL到http url

~/_docs/folder/folder/document.pdf 

我怎麼能在視圖中將其轉換爲超鏈接來下載文件本身?

感謝

回答

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

@Lorenzo,不用謝 :-) – 2010-09-28 20:46:26