ASP.NET Core 2.0 Tag Helper Component

Problem

How to dynamically write HTML using Tag Helper Components in ASP.NET Core 2.0.

Solution

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.

  1. public void ConfigureServices(IServiceCollection services)  
  2. {    
  3.       services.AddSingleton<ITagHelperComponent, MetaTagHelperComponent>();  
  4.       services.AddMvc();    
  5. }    
  6.     
  7. public void Configure(IApplicationBuilder app, IHostingEnvironment env)    
  8. {    
  9.       app.UseMvcWithDefaultRoute();    
  10. } 

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


Note that 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 the 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 a 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 the 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.

There is an interesting application of this for JavaScript logging here by Hisham.

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.

Source Code

GitHub