wolfgang ziegler


„make stuff and blog about it“

Image Tag Helper for ASP.NET MVC

July 9, 2012

ASP.NET MVC offers a big variety of helper methods for generating HTML tags, like <a>, <form> or the various HTML controls.

image One tag I have been missing though and need quite frequently is the <img> tag. Luckily, with the the help of .NET extension methods and the TagBuilder class we can craft our own helper methods with just a few lines of code:

public static class ExtensionMethods
  {
    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));
    }
  }

 

  1. We create a new static class which host our extension methods. Consequently we call it ExtensionMethods.
  2. We add the actual extension method called Image. Note the first argument is of type HtmlHelper, this is the object we access with the @Html syntax in our Razor views.
  3. Note also the return type of this method, which is of type MvcHtmlString. This type takes care of correctly HTML encoding our string, which keeps us safe from potential cross site scripting attacks.

Before we can start using our extension method we have to make sure that the namespace in which the extension class live gets included. This can be done for a single page with a using statement:

@using SomeNamespace

or globally by modifying web.config (for some reason this requires a restart of Visual Studio).

<namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="SomeNamespace" />
</namespaces>

Finally, we are good to go:

image