Getting started with Tag Helpers – ASP.NET 5

ASP.NET has been always near and dear to me and it got more exciting for me as ASP.NET5 got revolutionary changes comparing to previous versions. All the changes has been done considering key points that are driving the software evolution like Agility, embracing latest design standards and technologies. It provides more capabilities, more power to developer, follows latest standards and helps in writing Cloud and mobile ready applications. As we know ASP.NET is like a umbrella of technologies and consists of ASP.NET MVC, ASP.NET WebForms, ASP.NET web api etc. All these technologies got lots of change and design to serves the modern web apps. ASP.NET5 comes with another new version of ASP.NET MVC6. I will be writing couple of posts on cool features of ASP.NET 5 that actually makes our life easy as a developer.

In this post, I am going to discuss one of the main features of ASP.NET 5 that I really liked a lot. When razor syntax was introduced, it looked different and sometimes uncomfortable to me. There were multiple reasons. First thing, I loved the idea of writing C# code at in different file as code behind because it gave clear separation of markup and c# code. It also provided to leverage the real IDE power like intellisense for html, css, JavaScript, other plugins and was easily integrable with other plugins. Razor removed the concept of code behind and allows us to write to inline C# code. Although it is powerful at certain times but it is confusing sometimes as well and make a markup writing experience very bad. Because here we were not writing the HTML actually we were writing a mix and match of html and some C# methods that renders the html while executing at run time. So we used to get the issues while running the code only.

We have used a inbuilt HTML helpers in razor forms a lot and created custom helpers when required. Our normal Razor view looks like

<div class="editor-label">
// For Label
@Html.Label("Name", new {id= "lblName"}
<div class="editor-field">
// For textbox
// For action link
<li>@Html.ActionLink("Home", "Index", "Home")</li>
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
    @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

In above example, top three html helpers : for label, textbox and link are loosely typed view and last sectionis part of a  strongly typed view .  As earlier mentioned, we can see that it is combination of HTML and inline C# which we start with @. While rendering these html helpers methods gets called which returns the html that is rendered in browser.

ASP.NET 5 introduced new features named as TagHelpers. This is going to make developers life very easy and make the form, readable, maintainable and manageable.

First thing how to use

As we all know that in ASP.NET 5, the features were developed as independent components and can be added on demand via nuget. So we need to add it via nuget.

  1. Add Microsoft.AspNet.Mvc.TagHelpers

2 Then add it in View where you want to use this feature as @addtaghelper “Microsoft.AspNet.Mvc.TagHelpers”

Now I can use the awesomeness of tag helpers in our view. We can remove the below line

@Html.LabelFor(m => m.UserName, new { @class = “col-md-2 control-label” })

and instead can use

<label for=”UserName” class=”col-md-2 control-label” style=”color:red”></label>

It will work same as HTML helper. Under the hood the tag helper convert it to similar earlier lambda expression to get the property name.

Similarly for input

@Html.TextBoxFor(m => m.UserName, new { @class = “form-control” })

can be replaced with

<input form=”UserName” class=”form-control” style=”color:red” />

I have taken register page of starter web application which is as

razor-registerLooks as below after replacing normal razor syntax with tag helpers

taghelper-registerThis is awesome right. Now it looks cleaner, manageable and the best thing is you’ll get all the intellisense feature for HTML, css, javascript etc.

It’s not just yet. It also gives us power of creating our own tag helpers which we can create based on our need and render the appropriate html at runtime.

How to create Custom Tag Helper :

Creating custom tag helper is very easy. One need to create a class that inherits TagHelper class. So here we need to override one of these methods

1-  public override void Process(TagHelperContext context, TagHelperOutput output)

2-  public override void ProcessAsync(TagHelperContext context, TagHelperOutput output)

ProcessAsync is the asynchronous method that we can use if we need to do some long operations like getting data from database, calling any third party services etc. It has two parameters of .type TagHelperContext and TagHelperOutput. TagHelperContext  context contains the execution context for Taghelper and TagHelperOutput that contains the information that is required to generate the html. Here we provide all the details of html tags that will be generated while rendering

So for an example, I am going to create a simple status tag helper which displays different color based on some data. So my custom tag helper looks like

    public class StatusTagHelper : TagHelper
        public override void Process(TagHelperContext context, TagHelperOutput output)
            int status;
            output.TagName = "img";
            Int32.TryParse(context.AllAttributes["val"].ToString(), out status);
            if (status == 0)
                output.Attributes["src"] = "images/green.png";
            else if (status == 1)
                output.Attributes["src"] = "images/red.png";
                output.Attributes["src"] = "images/blue.png";

This custom tag is used as

<div class="form-group">
    <label class="col-md-2 control-label"> Status</label>
    <div class="col-md-10">
        <status val="1"></status>

Now if we see the C# code then you can find that attribute val is read from the context object and the details of the HTML tags are provided with the output object. One other item, you must be seeing the ContentBehavior attribute, what is the need? It plays a vital role in the tag helper. It tells that the way tag helper would render. Like here, I have used Replace, which means the tag used in cshtml will be replaced. There are four other options – None, Prepend, Append, Modify. It behaves as the name suggests, I will leave this for you guys to explore.

Let’s see the code running

customtaghelperHere the val is assigned to 1 and based on that image is rendered.

This is a simple example that I showed here to explain the Tag Helper. Creating taghelper is very simple and very flexible. Hope you have enjoyed the post. Wait for more articles on ASP.NET 5.

Happy Learning,


5 thoughts on “Getting started with Tag Helpers – ASP.NET 5

  1. Pingback: What is View component: ASP.NET 5 | Code Wala

  2. Pingback: Your Dependency Injection ready ASP.NET : ASP.NET 5 | Code Wala

  3. Pingback: VSLive 2015 in Austin, TX! - Madison Web Design, Wordpress Services, and Search Engine Optimization

  4. Pingback: Exploring ASP.NET Core View Component | Code Wala

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s