views:

263

answers:

2

Hello SO:

I have a Html Helper file for my ASP.NET MVC application. The majority of them simply 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 a TagBuilder version 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 I have been reading/learning about MVC from mix up implementations. Some use the TagBuilder method, others use string.Format(), and some use both interchangeably.

The label tag is rather simple, so would it be 'better' to just return a formatted string rather than instantiate the TagBuilder class for tags like this one?

I am not necessarily worried about performance, I am just curious as to why some choose TagBuilder and others use formatted strings.

Thanks for the enlightenment!

+2  A: 

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 appending the angle brackets. It essentially does the same thing as your code is doing so, if you only have one attribute, your way might be just as convenient.

Tagbuilder is used internally by the HTML Helpers.

Robert Harvey
alright thank you!
Anders
+3  A: 

Using TagBuilder will allow you to merge attributes on the tag. For example, using String.Format, if you want to conditionally have the CSS Class attribute on a tag, you'll need to do something like:

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

Whereas with a TagBuilder, you can use MergeAttributes() passing in a dictionary of keys/values. Pop open Reflector (or grab the source) and look at the System.Web.Mvc.Html.InputHelper() to get an idea of the power of using a builder with a lot of conditional attributes.

Both can result in the same output, but it really depends on what you're looking to achieve. It also depends on which you consider to be "cleaner" code.

Agent_9191
very good point. i think i may 'hybrid' my helpers file, make the simple ones a formatted string and the more complex ones TagBuilders.
Anders