ASP.NET Tag Helpers – Making HTML More Cool!

I’ve been at the AngleBrackets conference this week giving several talks and hanging out with the ASP.NET team members at the event.  We’ve had several great conversations about the new ASP.NET Tag Helpers functionality in the just announced ASP.NET 5 release.  That version is just in beta at this point, but we’re already contributing and getting great feedback on the direction for the framework.

I have several posts previously talking about Tag Helpers:

This time… lets talk about taking over control of a standard HTML tag and make it do something cool.  Yes… Jeff the Pirate is commandeering your HTML tags on the server, and YOU’LL LIKE IT!

Fixing Your Head

MaskIn this sample I’m going to hijack the HTML head tag to automatically inject references to script and css files appropriate for the other tag handlers in the assembly that I am referencing.  If I structure my tag helper with a class name of HeadTagHelper, by convention the framework will intercept the tag and apply any functionality that I define in my c-sharp class.  Otherwise, the TagNameAttribute can be used to force the tag helper to identify the HEAD tag.

[TagName("head")] // not needed, by convention pulls from class name
[ContentBehavior(ContentBehavior.Append)]
public class HeadTagHelper : TagHelper

In this sample, I’ve made doubly sure that the tag helper is going to trap the head tag.  I have also added the content behavior attribute to indicate that I want to append content to the content of the head tag.

I then implemented a Process method that appends references to the scripts and stylesheets that I need in my web project:

public override void Process(TagHelperContext context, TagHelperOutput output)
{

var sb = new StringBuilder();

sb.Append(@""); output.Content = sb.ToString(); }

That’s fairly straightforward content that I’m assembling.  When the content on the output object is set, that is appended (remember the ContentBehavior attribute) to the content of the head tag.

Summary

That’s it!  By defining a tag with the same name as a standard HTML tag, I have created an automatic injection to support other tag helpers that I have available in my tag helper class library.  Think about it:  you can write tag helpers to replace and enhance the behavior of the TABLE tag… you could for the table tag to always have a bootstrap css class of table-striped applied.  You could replace table tags with div and span tags because you hate tables.   Take a look at what you can do with tag helpers and give it a shot.