Reputation: 488
I'm working on my company's intranet site, On one of the pages I need to include links to .PDF files if they exist. No problem, I got that to work well enough. The problem I'm having is changing the link if the .PDF doesn't exist. Here's what I currently have:
, grid.Column(format: (item) => (File.Exists(item.FileName)==true ? @<a href="@Url.Content(item.FileName)">Art Work</a> : Html.Raw("")))
I'm receiving the errors: Argument 3: cannot convert from 'lambda expression' to 'System.Func'
AND The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments
I've done some due diligence with Google and can't find anything. Can someone tell me where I'm going wrong?
Upvotes: 2
Views: 2446
Reputation: 102408
Try something like this:
format: (item) =>
{
if (File.Exists(item.FileName))
{
return new HtmlString(string.Format("<a href=\"{0}\">Art Work</a>", @Url.Content(item.FileName)));
}
return string.Empty;
}
Upvotes: 0
Reputation: 1038780
I would definitely write a custom helper that will be responsible to generate the proper link:
public static class HtmlExtensions
{
public static IHtmlString LinkToFile(
this HtmlHelper htmlHelper,
string filename
)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var file = htmlHelper.ViewContext.HttpContext.Server.MapPath(filename);
if (!File.Exists(file))
{
return MvcHtmlString.Empty;
}
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = urlHelper.Content(filename);
anchor.SetInnerText("Art Work");
return new HtmlString(anchor.ToString());
}
}
and then inside the view simply use this helper:
grid.Column(format: @<text>@Html.LinkToFile((string)item.FileName)</text>)
Upvotes: 1