我需要显示指向文件的链接,但前提是该文件存在。到目前为止,我已经尝试扩展UrlHelper,HtmlHelper和MvcHtmlString,但是它们似乎都没有提供我需要的结果。
我确定我做错了什么,但我不知道那是什么。UrlHelper扩展似乎很接近,但是View将链接显示为文本而不是锚点。
public static class UrlHelperExtensions
{
public static string Pdf(this UrlHelper helper, string fileName, string directory)
{
string _fileName = fileName + ".pdf";
string _directory = directory + "/";
string root = "~/Content/Templates/";
string path = HttpContext.Current.Server.MapPath(root + _directory + _fileName);
if (File.Exists(path))
{
return helper.Content("<a href=\"" + root + _directory + _fileName + "\" target=\"_blank\">Download Template</a>");
}
else
{
return "";
}
}
}
然后@Url.Pdf(Model.Item.Number, "Retail")
给我文字
<a href="~/Content/Templates/Retail/1001.pdf" target="_blank">Download Template</a>
在页面上,而不是实际的链接上。
您必须HtmlString
像这样使用:
public static HtmlString Pdf(this UrlHelper helper, string fileName, string directory)
{
string _fileName = fileName + ".pdf";
string _directory = directory + "/";
string root = "~/Content/Templates/";
string path = HttpContext.Current.Server.MapPath(root + _directory + _fileName);
if (File.Exists(path))
{
return new HtmlString(helper.Content("<a href=\"" + root.Replace("~", "") + _directory + _fileName + "\" target=\"_blank\">Download Template</a>"));
}
else
{
return new HtmlString("");
}
}
编辑:修复了root
字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句