Creating Custom HTML Helpers in ASP.Net MVC 5

The intent of this article is to explain how to create custom HTML Helpers, so that we can use within the MVC views, using HTML Helpers class we can reduce the large amount of typing of HTML tags.

HTML Helpers

A HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.

The following are some of the standard HTML Helpers already included in ASP.NET MVC:

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()
Creating HTML Helpers with Static Methods

The easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create some new HTML Helpers that render an HTML <Image> tag, HTML <ActionLink> tag, HTML <ActionLinkSortable> tag, HTML <DisplayAddress> tag and HTML < label> tag.
  1. public static class HtmlHelpers   
  2. {   
  3.      /// <summary>  
  4.      /// Creates an Html helper for an Image  
  5.      /// </summary>   
  6.      /// <param name="helper"></param>   
  7.      /// <param name="src"></param>   
  8.      /// <param name="altText"></param>   
  9.      /// <returns></returns>   
  10.    
  11.      public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText)   
  12.      {   
  13.          var builder = new TagBuilder("img");   
  14.          builder.MergeAttribute("src", src);   
  15.          builder.MergeAttribute("alt", altText);   
  16.          return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));   
  17.      }   
  18.    
  19.      //create an action link that can display html   
  20.    
  21.      public static MvcHtmlString ActionLinkHtml(this AjaxHelper ajaxHelper, string linkText, string actionName,   
  22.  string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)   
  23.      {   
  24.          var repID = Guid.NewGuid().ToString();   
  25.          var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes);   
  26.          return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText));   
  27.      }   
  28.    
  29.      //create an action link that can be clicked to sort and has a sorting icon (this is meant to be used to create column headers)   
  30.    
  31.      public static MvcHtmlString ActionLinkSortable(this HtmlHelper helper, string linkText, string actionName,   
  32.  string sortField, string currentSort, object currentDesc)   
  33.      {   
  34.          bool desc = (currentDesc == null) ? false : Convert.ToBoolean(currentDesc);   
  35.          //get link route values   
  36.          var routeValues = new System.Web.Routing.RouteValueDictionary();   
  37.          routeValues.Add("id", sortField);   
  38.          routeValues.Add("desc", (currentSort == sortField) && !desc);   
  39.          //build the tag   
  40.          if (currentSort == sortField) linkText = string.Format("{0} <span class='badge'><span class='glyphicon glyphicon-sort-by-attributes{1}'></span></span>", linkText, (desc) ? "-alt" : "");   
  41.          TagBuilder tagBuilder = new TagBuilder("a");   
  42.          tagBuilder.InnerHtml = linkText;   
  43.          //add url to the link   
  44.          var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);   
  45.          var url = urlHelper.Action(actionName, routeValues);   
  46.          tagBuilder.MergeAttribute("href", url);   
  47.          //put it all together   
  48.          return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));   
  49.      }   
  50.    
  51.      //custom html helper to output a nicely-formatted address element   
  52.    
  53.      public static MvcHtmlString DisplayAddressFor<TModel, TProperty>(this HtmlHelper<TModel> helper,  
  54.  System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression, bool isEditable = false,   
  55.  object htmlAttributes = null)   
  56.      {   
  57.         var valueGetter = expression.Compile();   
  58.         var model = valueGetter(helper.ViewData.Model) as InGaugeService.Address;   
  59.         var sb = new List<string>();   
  60.         if (model != null)   
  61.         {   
  62.              if (!string.IsNullOrEmpty(model.AddressLine1)) sb.Add(model.AddressLine1);   
  63.              if (!string.IsNullOrEmpty(model.AddressLine2)) sb.Add(model.AddressLine2);   
  64.              if (!string.IsNullOrEmpty(model.AddressLine3)) sb.Add(model.AddressLine3);   
  65.              if (!string.IsNullOrEmpty(model.City) || !string.IsNullOrEmpty(model.StateRegion) ||  
  66.  !string.IsNullOrEmpty(model.PostalCode)) sb.Add(string.Format("{0}, {1} {2}", model.City,  
  67.  model.StateRegion, model.PostalCode));   
  68.              if (model.IsoCountry != null) sb.Add(model.IsoCountry.CountryName);   
  69.              if (model.Latitude != null || model.Longitude != null) sb.Add(string.Format("{0}, {1}",  
  70.  model.Latitude, model.Longitude));   
  71.          }   
  72.    
  73.          var delimeter = (isEditable) ? Environment.NewLine : "<br />";   
  74.          var addr = (isEditable) ? new TagBuilder("textarea") : new TagBuilder("address");   
  75.          addr.MergeAttributes(new System.Web.Routing.RouteValueDictionary(htmlAttributes));   
  76.          addr.InnerHtml = string.Join(delimeter, sb.ToArray());   
  77.          return MvcHtmlString.Create(addr.ToString());   
  78.      }   
  79.      public static string Label(string target, string text)   
  80.      {   
  81.          return String.Format("<label for='{0}'>{1}</label>", target, text);   
  82.      }   
  83.    
  84.      //Submit Button Helper   
  85.      public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)   
  86.      {   
  87.          string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";   
  88.          return new MvcHtmlString(str);   
  89.      }  
  90.  } 

 

Up Next
    Ebook Download
    View all
    Learn
    View all