MVC custom Image HtmlHelper method with Default image options

I am new to MVC and I am continously sharing my best experience while learning MVC. Today I came with another well known MVC problem- Show default Image if image not found in MVC. After several fruitful search i found some good code example which is easily resolve our problem. 
In this article i am sharing custom Image HtmlHelper class which will handle all Image options like default image, alt text and css class. We modify existing code and make image HtmlHelper method for more customize use. You can set src , alt text and css class. This custom image HtmlHelper method will set Default image file if original image is not found on stored location.
public static MvcHtmlString Image(this HtmlHelper helper, string src, string alt,string cssclass)
  var builder = new TagBuilder("img");
  UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
  if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(src)))
    src = urlHelper.Content("~/content/images/none-image.png");
    src = urlHelper.Content(src);

  builder.MergeAttribute("src", src);
  builder.MergeAttribute("alt", alt);
  builder.MergeAttribute("class", cssclass);
  return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
How to Use
 @Html.Image(Model.Image ,"alt text","img")
when you are using custom Image helper method first resolve reference in View. We have pass m.Image as src , alt and class  are optional you may pass blank.
If you are using same view for Create and Edit then you must check your model is null or not (see example below).
 @Html.Image(Model == null ?"": Model.Image ,"Alt text","img")


Popular posts from this blog

12 opensource and free MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in