One Thing I’ve Learned Today: MVC Custom HtmlHelper

This week, I’ve spent some time learning MVC and one of the things I was trying to do was to display an image given the path to an image file. Using an <img /> tag in a Razor view seemed crude and less than optimal. That’s when I started watching the MVC PluralSight course offered for free here.

I wanted to be able to use

 @Html.Image(item.ImageUrl, item.Name)

 

Unfortunately, no such thing exists out of the box. However, making this work is surprisingly straight-forward:

Create a custom HtmlHelper class.

using System.Web.Mvc;

namespace MvcApplication1.Infrastructure
{
	public static class HtmlHelpers
	{
		public static MvcHtmlString Image(this HtmlHelper helper,
			string src, string altText)
		{
			var builder = new TagBuilder("img");
			builder.MergeAttribute("src", src);
			builder.MergeAttribute("alt", altText);
			return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
		}
	}
}

Now, all I need to do is add a using statement to my view and add my Image tag where needed:

@using MyProject.Infrastructure
 ... blah blah blah...
 @Html.Image(item.ImageUrl, item.Name)


Quick, simple, and elegant. And if this custom HtmlHelper class is used in more than one view, you may want to forego the adding of the using statement in the view and instead, modify the Views\Web.config file and add the namespace to the list of namespaces defined for razor.