Display Default Image when No Image Found MVC Razor View Engine

This is very useful questions, very often we required it.
I pick this from stack-overflow forum

"I have a asp.net mvc project. in a specific views i call the four image from different different folder inside my project.
sometime image can not be found. i want to set a image for every folder because all 4 folder contain different different size of image so i need to set the image of specific size for each folder.
how i can show the default image when the image not found any way to do that.i means call the none.png when the directory not have image who i called in the views.
are their any way to show the image in the case of image not found.
any way to do that in asp.net 4 MVC 3. using web.config or setting anything else."

Best Answers:
Easiest way to do this is with a html helper. Please be mindful of the extra performace hit of checking the file system before even showing an image filename. The hit is a small one though, so you won't notice any issues unless you are getting very high traffic. Then you can implement some sort of caching so the app "knows" if the file exists or not.
You can use a custom html helper for it
        public static class ImageHtmlHelpers
            public static string ImageUrlFor(this HtmlHelper helper, string imageFilename, ImageSizeFolderEnum imageSizeFolder)
                UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
                string contentUrl = String.Format("~/content/userimages/{0}/{1}", imageSizeFolder, imageFilename);
                if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
                    return urlHelper.Content(String.Format("~/content/userimages/{0}/none.png", imageSizeFolder));
                    return urlHelper.Content(contentUrl);


Then in your view you can just make the url using:

<img src="<% Html.ImageUrlFor("myimage.jpg", ImageSizeFolderEnum.Small); %>" />

Have suggested an Enum for better programmatic control if the folder is a fixed set, but for a quick and nasty approach, not reason why you can't just use a string if the folder is db generated etc.



Contact Form