.NET Core - MVC

Observations about .NET Core, MVC and converting YetaWF from ASP.NET MVC5 to .NET Core MVC. The new .NET Core has great new features. Getting there from an existing MVC 5 app is HARD!

TagBuilder ToString()

02/07/2017

YetaWF has a fair number of templates which are used with the UIHint attribute - And a lot of code generating the required HTML for the templates. In MVC5, the TagBuilder class was used to build HTML tags. Once all tag attributes are set, the ToString() method was used to generate the tag HTML string. Unfortunately, the TagBuilder.ToString() method in ASP.NET Core MVC is not implemented, so the object.ToString() method is used instead. This of course does not generate anything resembling an HTML string. Instead, you get something like "Microsoft.AspNetCore.Mvc.Rendering".

Old Code:

TagBuilder tag = new TagBuilder("span");
string html = tag.ToString();

Sadly, when converting to MVC6 there is no compile error or any other indication that things went wrong.

Creating an extension method for the TagBuilder class with a new ToString() method doesn't work as that doesn't override the existing object.ToString() method.

Your only option is to manually find all uses of TagBuilder.ToString() and change them to ToString(TagBuilder.Normal). Good luck, hope you don't miss one...

TagBuilder tag = new TagBuilder("span");
string html = tag.ToString(TagBuilder.Normal);

The recommendation given is to use HtmlString instead. But the whole point of upgrading an existing application is to do so with minimal code changes, and certainly without quietly breaking code!

It would have been simple enough to keep TagBuilder.ToString() without any adverse effects. It's disappointing that this new version of ASP.NET Core MVC does not seem to care about compatibility.

No Comments

Be the first to add a comment!

Add New Comment

Complete this simple form to add a comment to this blog entry.