Adding a custom HTML Helper to .Net Core
As promised last time, I’m going to talk about HTML helpers on ASP.NET Core. If you’ve never heard about helpers before you may be thinking about another kind of helper perhaps:
However, I’m talking about the kind of helper which helps you write code once and re-use it in multiple places. The two biggest advantages with helpers are that they keep the page output consistent and when the time comes to change something you only need to change it in one place. Code repetition is not good and never fun.
Tag helpers seem to be the cool thing to do with .NET Core, but remember that I am looking to convert the site from MVC 5 with minimal changes and if possible do everything without touching the views.
The first required adjustment was to change the helper type to IHtmlHelper and the return type to IHtmlContent. That is good since in both cases the change is minimal, and because by using interfaces the helper is not directly dependant on any particular type as long as the type implements the interface.
The major problem that I faced was with the TagBuilder’s InnerHtml property: it’s readonly. No big worries though. Once I noticed that this was a dead end, changing the helper to build the content via a StringBuilder instead proved to be very easy. The last fix was to change the return object from MvcHtmlString to HtmlString.
Once that was done, it was just a case of running the solution and this permitted me to confirm that everything was actually working as wanted.
One final step that I want to sneak in is adding Application Insights to the solution. We are almost done with the changes, so adding monitoring to start gathering some data makes sense at this point. There is also tooling in Visual Studio to help with this. The easiest way is to right-click on the project and Add > Application Insights. Since I was already using Insights on the previous solution, this was also detected and the existing instrumentation key was easily picked up and configured by the editor. Next time, let’s get ready to publish the changes!