Tag Helper Component in ASP.NET Core 2.0

Tag Helper Component in ASP.NET Core 2.0

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 2.0 hosting. How to dynamically write HTML using Tag Helper Components in ASP.NET Core 2.0 ? In this post we will discuss about Tag helper component in ASP.NET Core 2.0

Create an empty project and add a controller:

Add a view:

Add a Tag Helper Component:

Update the Startup class, inject the component class to service container:

Run and observe the page generated (view source or developer tools in browser):

meta

Note that the two meta tags were dynamically generated by the Tag Helper Component.

Discussion

ASP.NET Core 2.0 has introduced “Tag Helper Components” that improve and complement Tag Helpers by giving developers capability to use Dependency Injection with them.

The way this works is that:

  1. We create a Tag Helper to target existing or new (i.e. custom) HTML elements.
  2. We then create a class that inherits from TagHelperComponent and override its Process() method to append HTML content to the Tag Helper’s HTML element.
  3. We then inject this class into the service container, which is executed at runtime.

In case you’re wondering if the solution above is missing a Tag Helper for head HTML element, it’s not. ASP.NET Core team has provided us with two built-in Tag Helpers, one targets head and the other targets the body element: HeadTagHelper and BodyTagHelper

In the solution above our Tag Helper Component is adding few meta tags to the head element. This could be used, for instance, by a blogging engine to output them for search engine optimisation.

I’ve hard-coded entries but of course using Dependency Injection we can inject a service that could retrieve these from a database:

Another possible use-case for a Tag Helper Component, that targets head or body, is to dynamically inject scripts/styles e.g.:

There is an interesting application of this for JavaScript logging

Custom Tag Helpers & Components

We can use these components for custom Tag Helpers too. Let’s say we want to target all the footer elements and inject current time (or visitors count, logo, copyright etc.). We can first create a Tag Helper to target a footer element:

Note: the base class is the new TagHelperComponentTagHelper and not the TagHelper used for non-component scenarios.

Now we can create a Tag Helper Component that targets this Tag Helper: