Build html strings in HtmlHelper extension methods

Can someone be kind and explain why I should write lines this way:

public static MvcHtmlString Render(this HtmlHelper htmlHelper, MenuItem menuItem) { if (!menuItem.IsVisible) return MvcHtmlString.Empty; var li = new TagBuilder("li"); var a = new TagBuilder("a"); a.MergeAttribute("href", menuItem.Uri); a.SetInnerText(menuItem.Title); li.InnerHtml = a.ToString(); return MvcHtmlString.Create(li.ToString()); } 

If it is much cleaner:

  public static MvcHtmlString Render(this HtmlHelper htmlHelper, MenuItem item) { if (!item.IsVisible) return MvcHtmlString.Empty; var str = string.Format(@"<li><a href=""{0}"">{1}</a></li>", item.Uri, item.Title); return MvcHtmlString.Create(str.ToString()); } 

What are the benefits?

+4
source share
2 answers

There is no great reason. I would say speed, because TagBuilder is essentially a specialized StringBuilder , which is known to be faster than string.Format , but I will need to see some benchmarks, since it seems that the whole structure of the HTML object can slow down.

One example of why you can use it is that it simplifies conditional logic. I think, for example, something like

 var theClass = item.Title.Length > 5 ? " class=\"Long\"" : ""; var str = string.Format(@"<li><a href=""{0}""{1}>{2}</a></li>", item.Uri, theClass, item.Title); 

not very clear or clean, whereas

 if (item.Title.Length > 5) { a.AddCssClass("Long"); } // And then all that other stuff. 

- a pretty nice solution.

+4
source

TagBuilder simply ensures that your HTML is well-formed. I use tagbuilder for everything that I would use for multiple lines in HTML, for example, within the href inside a div for added protection against typos.

+1
source

All Articles