How to display a default image in case the source does not exists
15,585
Solution 1
It's far better to handle this server-side:
public static class HtmlHelperExtensions
{
public static string ImageOrDefault(this HtmlHelper helper, string filename)
{
var imagePath = uploadsDirectory + filename + ".png";
var imageSrc = File.Exists(HttpContext.Current.Server.MapPath(imagePath))
? imagePath : defaultImage;
return imageSrc;
}
private static string defaultImage = "/Content/DefaultImage.png";
private static string uploadsDirectory = "/Content/uploads/";
}
Then your view is simplified to:
<img src="@Html.ImageOrDefault(item.ID)" />
Solution 2
Sure, for your images use:
<img src="fails/to/load.png" onerror="this.src='path/to/replacement/image.jpg'" />
There isnt a solution in CSS, it will require JS to be either applied to each <img>
tag or a top level handler to replace the onerror
event for all images.
Author by
John John
Updated on June 09, 2022Comments
-
John John almost 2 years
I have the following code inside myasp.net MVC web application:-
<a href="~/Content/uploads/@(item.ID).png"><img class="thumbnailimag" src="~/Content/uploads/@(item.ID).png" /></a> @Html.ActionLink(item.Name,"Details","DataCenter", new{id = item.ID},null)
And the following CSS:
.thumbnailimag { width:30px; height:30px; border:thin blue; background-image:url("/Content/uploads/virtual-data-center.jpg"); }
But if the image does not exists each bowser will treat it differently . I set a background image but still on IE it will display a “X” over the default image , as follow:-
Can anyone advice if there is a way to display a default image if the src does not exists?
-
Praveen over 10 years+1 though I fear if error.jpg does not exist
-
John John over 10 yearsbut where it is better to create this class, under the Controller folder or under the Model folder ? thnaks
-
John H over 10 years@JohnJohn I tend to create a new folder called
Extensions
orHelpers
and put it in there. In order for that to work though, you'd need to add the namespace to your~/Views/Web.config
file (make sure it's that one and not theWeb.config
in the root of your project). Just look for the element<system.web.webPages.razor>
. In there, you'll find a few namespaces already added. Under those, you'd add something like:<add namespace="YourProject.Extensions" />
. -
kwoxer about 9 yearsEasy and best solution! Thanks.
-
Jim about 9 years+1 Thanks @SW4 (and John John for asking the question) saved me a bunch of time/code/experimentation/failure/heartbreak.
-
Rodrick Chapman over 7 yearsPerhaps
onerror="this.onerror = null; this.src='path/to/replacement/image.jpg'"