Reputation: 1362
I am trying to display a default image when the given image is not found. As my code is now, it always shows the default image. Can I not use Url.Content
in File.Exists()
?
Here is my code:
@if (File.Exists(Url.Content("~/Content/img/" + item.name + ".jpg")))
{
<img src="@Url.Content("~/Content/img/" + item.name + ".jpg")" alt="@item.longname" />
}
else
{
<img src="@Url.Content("~/Content/img/default.png")" alt="@item.longname" />
}
Upvotes: 0
Views: 121
Reputation: 156998
First, I would suggest to move this code into a Controller or external class to make it more readable.
Use Server.MapPath
to get the real file name of the url.
That file path can be checked with File.Exists
.
Upvotes: 1
Reputation: 223287
You need Server.MapPath
like:
File.Exists(Server.MapPath("~/Content/img/" + item.name + ".jpg"))
Upvotes: 2