Tag Helpers allow server-side code to participate in the rendering of HTML elements in Razor files. In this regard they are similar to HTML Helpers methods, the biggest difference is that Tag Helpers actually attach to HTML elements in your Views rather than being called as methods that have been embedded within the HTML.

Tag Helpers can be designed to target HTML they affect by either element name or element attributes. The key thing here for me is that it helps reduce those jarring transitions between HTML and C# in your Razor files. A big bonus is that Visual Studio is a able to provide HTML highlighting that makes it clear that a Tag Helper is beening used.

Authoring a Tag Helper

Tag Helpers are classes that implement the ITagHelper, this interface has one method Process , there is no complex life cycle to concern yourself with, there is just a simple context object, and an output object that eventually gets passed back to the browser. So here is an example::

TargetElement("a", Attributes=TwitterAttributeLink)]
public class TwitterTagHelper : TagHelper
{
// the name of attribute has been moved to a variable to keep things DRY
private const string TwitterAttributeLink="gravatar-twitter";

[HtmlAttributeName(TwitterAttributeLink)]
public string TwitterHandle { get; set; }


public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes["href"] ="http://twitter.com/" + TwitterHandle;
}
}

This Tag Helper is designed to attach to anchor tags only as defined by the TargetElement, it simply takes the attribute defined as “gravatar-twitter” and uses it to create a href attribute on the anchor tag.

So your Razor file would like this:

This would produce the following href tag on the anchor tag:

I must admit this particular example is not particularly helpful but I think this would be a much more powerful option in future version of dasBlog for creating “macros”. Documentation on Tag Helpers can be found here, and the work being currently being done on Razor is hosted on GitHub.



Comment Section

Comments are closed.