Tag Archives: Razor

Authoring ASP.NET 5 Tag Helpers

One of the biggest updates to Razor views in ASP.Net 5 (MVC 6) is TagHelpers. TagHelpers by and large replace HTML Helpers for generating snippets of dynamic HTML.

Why HTML Helpers are Being Replaced

HTML Helpers were helpful in that they gave you a way to generate HTML from strongly typed models, but they did it in a way that couldn’t take advantage of the rich HTML editor in Visual studio. For example to generate an link to your homepage with a CSS class you would write something like this:

@Html.ActionLink("About Me", "About", "Home", null, new { @class="btn btn-primary" })

Because the class is declared inside a C# method your editor can’t help you with CSS class intellisense. Furthermore, it’s a clumsy syntax that isn’t immediately obvious.

TagHelpers provide a more HTML native way to generate tags, while providing even greater support for strongly-typed views. A TagHelper implementation of the above example would look like:

<a asp-controller="Home" asp-action="About" class="btn btn-primary">About Me</a>

HTML Helpers are still available in ASP.Net 5 for backwards compatibility, but new views will benefit from TagHelpers.

Authoring a Gravatar TagHelper

The rest of this blog post will be about implementing a custom TagHelper to display a Gravatar profile picture. Gravatar is a service that hosts profile pictures that can be used across third-party websites. Those websites can display a profile image by computing an MD5 hash of the user’s email address. For example my email is pnewhook@infusion.com, which can be turned into the profile image found at http://www.gravatar.com/avatar/fae2af75c8c0ca925a229678b528bb04.

First you’ll need the latest version of Visual Studio 2015, or the command line tools found at the ASP.Net Home GitHub repository.

Defining the TagHelper

TagHelpers are C# classes that inherit from the abstract Microsoft.AspNet.Razor.Runtime.TagHelpers.TagHelper class, which is in the Microsoft.AspNet.Mvc.Razor assembly available on NuGet.You can implement a TagHelper in a class inside your ASP.Net 5 project, or in another assembly.

We also want to add the TargetElement attrubte to tell Razor which HTML tag this TagHelper applies to. We’re going to target the plain <img> tag, though we could just as easily create a custom tag. Furthermore, we want Razor to ignore regular <img> elements. We can do this by specifying the optional Attributes parameter in the TargetElement attribute. In my case I’ve specified my Gravatar tags will have a gravatar-email attribute. Our new class will look something like this.

[TargetElement("img", Attributes="gravatar-email")]
public class GravatarTagHelper : TagHelper


A note about naming conventions

You may have noticed that the TagHelpers that ship with MVC use an asp- prefix for attributes. That was purely a design choice by the ASP.Net team to differentiate TagHelper attributes from normal attributes. Native attributes that supplement native HTML tags (<a>, <link>, <input>) will be prefixed with asp- whereas attributes on custom TagHelpers (<cache>) won’t be prefixed.
In you own TagHelpers you’re free to prefix as you choose, though the prefixs for augmentative attributes is a good pattern to follow.

Getting Inputs from HTML Attributes

The easiest way to read from the HTML attribute is to use the HtmlAttributeName attribute. This will cause the value of the HTML attribute to be assigned to the property.

[TargetElement("img", Attributes=EmailAttributeName)]
public class GravatarTagHelper : TagHelper
    // the name of attribute has been moved to a variable to keep things DRY
    private const string EmailAttributeName="gravatar-email";
    public string EmailAddress { get; set; }

Generating the Profile Hash

TagHelper defines a pair or methods that are used to turn the input into HTML: Process and ProcessAsync. Since we’re not dependent on any asynchronous calls, we’ll use the synchronous version, but it’s helpful that ASP.Net 5 Razor views can now call async methods.

Both process methods take two parameters, a TagHeplerContext and a TagHelperOutput. TagHelperContext is only necessary if you need the HTML that is generated between your TagHelper opening and closing tags. Our GravatarTagHelper doesn’t include any child content, so we won’t use the context parameter.

The TagHelperOutput will be what’s ultimately turned into an HTML tag. It has a number of properties that are assigned in your Process method That will be used to generate the HTML output. It may be a little odd to see TagHelperOutput as a paramater and not a return value, but designing it this way lets TagHelpers be chained together.

The contents of our Process method are mostly Gravatar specific. The email address property, which is set above, is converted to an MD5 hash string. If you’re following along, make sure you include System.Security.Cryptography.Hashing in your project.json. The TagHelper specific bit of code is setting the output.Attributes["src"] value. This value becomes the src attribute on the resultant img tag.

public override void Process(TagHelperContext context, TagHelperOutput output)
	using(var md5 = MD5.Create())
        byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(EmailAddress));
        // Build the final string by converting each byte
        // into hex and appending it to a StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<hash.Length;i++)
        output.Attributes["src"] ="http://www.gravatar.com/avatar/" +  sb.ToString();

Using your TagHelper

If you defined your TagHelper in a separate project from you web application you will need to do two things. First, reference your TagHelper project in the web project project.json.

Secondly you’ll need to import the TagHelper. This is done using the @addTagHelper directive in the _GlobalImport.cshtml. _GlobalImport.cshtml is a new file for MVC projects that lets you import directives into all your Razor views.

Now I can add a TagHelper to my Razor view with the following code:

<img gravatar-email="pnewhook@infusion.com">

And Razor will output the following HTML

<img src="http://www.gravatar.com/avatar/fae2af75c8c0ca925a229678b528bb04">


The biggest improvement to the Razor view engine in ASP.Net 5 is TagHelers. TagHelpers make it easy create reusable HTML snippets that can be shared across projects. TagHelers replace HTML Helpers with HTML native syntax, while still supporting strongly-typed views.

If TagHelpers seem similar to Angular directives, it’s not by accident. The ASP.Net team has said they were heavily influenced by directives, albeit in a server-side environment.

I you want to see a full implementation of a Gravatar TagHelper, or want something to use in your web sites, check out my gravatar-taghelper project on GitHub.