ASP.NET MVC ImageFor HtmlHelper

I have created the ImageFor HtmlHelper for use if the image url is stored in a database, web.config etc.

Helper:

using System.Linq.Expressions;
using
System.Web.Routing;

namespace
System.Web.Mvc
{
    public static class
HtmlHelpers
    {
        public static MvcHtmlString ImageFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression)
        {
            var imgUrl = expression.Compile()(htmlHelper.ViewData.Model);
            return BuildImageTag(imgUrl.ToString(), null);
        } 
        public static MvcHtmlString ImageFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            object htmlAttributes)
        {
            var imgUrl = expression.Compile()(htmlHelper.ViewData.Model); 
            return BuildImageTag(imgUrl.ToString(), htmlAttributes);
        }
 
        private static MvcHtmlString BuildImageTag(string imgUrl, object htmlAttributes)
        {
            TagBuilder tag = new TagBuilder("img");
 
            tag.Attributes.Add("src", imgUrl);
            if (htmlAttributes != null)
                tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
 
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
}

Usage:

In this example, the image url is stored in the web.config in appSettings.

  <appSettings>
    <
add key="ImageUrl" value="/Content/CSSiteLogo.gif"/>
  </appSettings>

Create a property in the model for the image url.

   
public class IndexModel
    {
        public string ImageUrl { get; set; }
    }


Fetch the image url from the web.config and pass the model to the View in the Action method.

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        IndexModel model = new IndexModel { ImageUrl = WebConfigurationManager.AppSettings["ImageUrl"] }; 
        return View("Index", model);
    }

In the View, use the ImageFor helper.

    @Html.ImageFor(model => model.ImageUrl, new { width="216px", height="70px", alt="some alt text" })
    OR 
    @Html.ImageFor(model => model.ImageUrl)

Result:

httphendler.gif