Search code examples
asp.net-mvcrazorasp.net-mvc-4asp.net-mvc-helpers

Is hardcoding a default nopic image in my MvcHelperExtension bad design


I've just written an MVC helper method to write img tags for me, in the method I'm hardcoding a nopic image that should be used when no image path is passed in. I don't like the hardcoding but don't know what the best approach I could use (given this is MVC and this is a helper) to achieve it would be.

public static MvcHtmlString Image(this HtmlHelper htmlHelper, 
                                  string imgName, string alt, int height)
{
    if (string.IsNullOrWhiteSpace(imgName)) imgName = "nopic.jpg";
    var src = String.Format("/Content/ProductImages/{0}", imgName);

    var tagBuilder = new TagBuilder("img");
    tagBuilder.Attributes.Add("src", htmlHelper.Encode(src));
    tagBuilder.Attributes.Add("alt", htmlHelper.Encode(alt));
    tagBuilder.Attributes.Add("height", htmlHelper.Encode(height));

    return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
}

Solution

  • I thing hard coding in programming is bad think because maintenance is so hard you can add key in web config and get it easy and if need too change it you can change it easy without publish again In web config:

    <add key="ImagePath" value="/Content/ProductImages/"/>
    

    In c# code:

    var path= WebConfigurationManager.AppSettings["ImagePath"].ToString()