I am migrating projects from .NET Framework to .NET core. This question is about ASP MVC projects. I have a lot of HtmlHelper extension methods and many of these use the TagBuilder class to generate HTML elements while generating content into a StringBuilder.
public static HtmlString DisplayTiles(this IHtmlHelper html, TileDashboardModel groups, bool displayNotEnabled = false, bool displayUnauthorized = false)
{
if (groups == null) throw new ArgumentNullException(nameof(groups));
var content = new StringBuilder();
var div = new TagBuilder("div");
content.AppendLine(div.ToString(TagRenderMode.StartTag)); // does not build
foreach (var group in groups.Groups)
{
DisplayTiles(html, content, group, displayNotEnabled, displayUnauthorized);
}
content.AppendLine(div.ToString(TagRenderMode.EndTag)); // does not build
////return new MvcHtmlString(sb.ToString()); // does not build
return new HtmlString(content.ToString());
}
In .NET Core the TagBuilder.ToString() method does not accept any argument. And rendering method seem to force you to use a StringWriter.
What ways would you change the code to make it work?
Consider: ease of change, memory consumption, extension method interference, code readability.
Related but different: Migrating TagBuilder core methods from ASP.NET MVC 5 to ASP.NET Core, How to display content of StringBuilder as HTML?
The ways I found are these, from the "best" to the worst. full code here
Initial code
This only works with .NET Framework.
Minimal changes
This method focuses on minimal changes. You only need to change one type and declare a 3 extension methods.
Minimal call stack
Here a focus on not using extra methods; code changes a lot.
The memory hogger
There is a known extension method that will allocate too much memory. Don't do this one.
Here is a variant using
TagRenderMode.