How to concatenate several MvcHtmlString instances

Too bad C# won’t let us override the + operator here! How about using an extension method instead?

public static MvcHtmlString Concat(this MvcHtmlString first, params MvcHtmlString[] strings)
{
    return MvcHtmlString.Create(first.ToString() + string.Concat(strings.Select(s => s.ToString())));
}

This could probably be optimized, but you can run with it. It should be fairly trivial to prove that this doesn’t double encode strings with a unit test.

Usage sample:

label.Concat(textbox, validation)   

And now a shameless plug for my blog: Use TagBuilder or HtmlTags to clean up your HTML

Leave a Comment