我有一个模型类的属性,它包含文件的相对URL。
~/_docs/folder/folder/document.pdf
如何在视图中将其转换为超链接以下载文件本身?
感谢
答案 0 :(得分: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" }
) %>