Search code examples
asp.net-core-mvc

How to concatenate MVC6 HtmlString


Similar to the old MvcHtmlString, I want to concatenate several instances HtmlString in MV6.

There doesn't seem to be an obvious way?

Perhaps the absence of such means I'm doing it wrong? The use case is I have the results of two TagBuilder instances that I want to concatenate as siblings before consuming inside of a TagHelper.


Solution

  • Taking the same path as the answer for concatenating an MvcHtmlString, I made an extension to concat a plain string and also n number of HtmlString

    public static class HtmlStringExtensions
    {
        public static HtmlString Concat(this HtmlString first, string plainString)
        {
            return Concat(first, new HtmlString(plainString));
        }
    
        public static HtmlString Concat(this HtmlString first, params HtmlString[] htmlStringsForConcat)
        {
            var sb = new StringBuilder();
            sb.Append(first);
            foreach (var htmlString in htmlStringsForConcat)
            {
                sb.Append(htmlString);
            }
            return new HtmlString(sb.ToString());
        }
    }