4

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also noteworthy are the MergeAttributes<> method and the InnerHtml getter/setter. Definitely, saves a lot of coding pain!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.