Reputation: 101150
Can someone be kind and explain why I should write strings in 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());
}
When this is so 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?
Upvotes: 4
Views: 2640
Reputation: 112857
There isn't a great reason. I would say speed, since TagBuilder
is essentially a specialized StringBuilder
, which is known to be faster than string.Format
, but I'd need to see some benchmarks, since it seems like the whole HTML structure thing might slow things down.
One example of why you might want to use it is that it makes conditional logic easier. 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);
is not very clear or clean, whereas
if (item.Title.Length > 5)
{
a.AddCssClass("Long");
}
// And then all that other stuff.
is a pretty nice solution.
Upvotes: 4
Reputation: 24754
TagBuilder just ensures your HTML is well formed. I tend to use tagbuilder for anything I would use multiple lines for in HTML like an span within a href within an div for the extra protection from typos.
Upvotes: 1