Friday, September 7, 2012

ASP.NET MVC Image Helper that accepts nulls

One of the things I liked about ASP.NET's ASP:Image tag was that it would not render an HTML image tag if the url was null. Using @Url.Content in an image tag throws an error, but I was able to easily accomplish the same behavior as ASP:Image using Razor with the following code (90%+ of the source is from this StackOverflow question):
   public static class ImageHelper  
   {  
     public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)  
     {  
       return Image(helper, id, url, alternateText, null);  
     }  
   
     public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)  
     {  
       MvcHtmlString ret;  
   
       if (url == null)  
       {  
         ret = null;  
       }  
       else  
       {  
         // Instantiate a UrlHelper   
         var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);  
   
         // Create tag builder  
         var builder = new TagBuilder("img");  
   
         // Create valid id  
         builder.GenerateId(id);  
   
         // Add attributes  
         builder.MergeAttribute("src", urlHelper.Content(url));  
         builder.MergeAttribute("alt", alternateText);  
         builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));  
   
         // Render tag  
         ret = new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));  
       }  
   
       return ret;  
     }  
   }  
I'm really just testing out different blog code formatting options, but I think this is at least a bit useful :-)