What is the difference, if any, between string.Format and TagBuilder in ASP.NET MVC?

I have an Html Helper file for my ASP.NET MVC application. Most of them just return a formatted string.

Here is an example of one of my formatted string helpers:

public static string Label(this HtmlHelper helper, string @for, string text) { return string.Format("<label for \"{0}\">{1}</label>", @for, text); } 

Here is the version of TagBuilder that gives me the same result as above:

 public static string Label(this HtmlHelper helper, string @for, string text) { var builder = new TagBuilder("label"); builder.Attributes.Add("for", @for); builder.SetInnerText(text); return builder.ToString(TagRenderMode.Normal); } 

Now, a few sites that I have read / learned about MVC from mixed implementations. Some use the TagBuilder method, others use string.Format() , and some use interchangeably.

The tag tag is pretty simple, so it would be β€œbetter” just to return a formatted string instead of instantiating the TagBuilder class for tags like this?

I'm not necessarily worried about performance, I'm just wondering why some choose TagBuilder and others use formatted strings.

Thanks for the enlightenment!

+4
source share
3 answers

Using TagBuilder will allow you to combine attributes in a tag. For example, using String.Format, if you want to conditionally have a CSS class attribute in a tag, you need to do something like:

 String.Format("<label {0}>Text</label>", (includeClass ? "class=\"Something\"" : "")); 

While with TagBuilder you can use MergeAttributes () passing in the key / value dictionary. Cover the open reflector (or capture the source) and look at System.Web.Mvc.Html.InputHelper () to get an idea of ​​the possibility of using a builder with many conditional attributes.

Both can produce the same result, but it really depends on what you want to achieve. It also depends on what you consider to be "clean" code.

+6
source

Tagbuilder is a convenience class. It stores a dictionary of your tag attributes and then outputs the HTML all at once. You also don't have to deal with adding angle brackets. This essentially does the same thing as your code, if you have only one attribute, your path may be just as convenient.

Tagbuilder is used internally with HTML helpers.

+2
source

TagBuilder handles the HTML encoding of attribute values: SetInnerText () encodes, .InnerHTML does not. Also, if you return a TagBuilder instead of a string, you can easily add a class or CSS attribute later in the stream.

Why use TagBuilder instead of StringBuilder?

0
source

All Articles