Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 440
Anders Avatar asked Mar 01 '23 06:03

Anders


2 Answers

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.

like image 193
Agent_9191 Avatar answered Apr 30 '23 11:04

Agent_9191


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.

like image 33
Robert Harvey Avatar answered Apr 30 '23 13:04

Robert Harvey