Saturday, January 2, 2010

Creating custom HTML helpers for ASP.NET MVC

Creating your own HTML helpers for ASP.NET MVC is very easy. If you understand extension methods and know how to use the TagBuilder class, you’re good to go.

A simple example creating a HtmlHelper method to render image tags:

   1:  public static class HtmlHelperExtensions   
   2:  {   
   3:          public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)   
   4:          {   
   5:              // Create tag builder   
   6:              var builder = new TagBuilder("img");   
   7:                 
   8:              // Create valid id   
   9:              builder.GenerateId(id);   
  10:    
  11:              // Add attributes   
  12:              builder.MergeAttribute("src", url);   
  13:              builder.MergeAttribute("alt", alternateText);   
  14:              builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));   
  15:    
  16:              // Render tag   
  17:              return builder.ToString(TagRenderMode.SelfClosing);   
  18:          }   
  19:    
  20:  } 

And if you don’t know where to start, check the  Using the TagBuilder Class to Build HTML Helpers tutorial.

No comments: