Tag Helpers in ASP.NET 5

The version 6.0 of the MVC framework (Model View Controller) in ASP.NET 5.0 provides a new approach for reusable components in the form of so-called Tag Helpers (not to be confused with HTML Helpers that are already available in ASP.NET MVC since version 1.0). Software developer can now define a new HTML tag or extend existing ones, which will be replaced on the server side before delivering the HTML page to the client.

This is comparable to the directives in angularjs. However, angularjs is a JavaScript framework that translates on the client side (ie in the browser).

 

In Short:

Basically TagHelper allow you to create own server side tags in your Razor views. It's far less complex and feels much more like second nature.

 

 So this

@Html.ActionLink("About us", "About", "Home")

 Can now be written as

<a asp-controller="Home" asp-action="About">About us</a>

 

The HTML result in both cases is

<a href="/Home/About">About us</a>

 

 

Define your own Tag Helper:

Let's write a simple Tag Helper. I assume that most people know about Twitter Bootstrap. It's a column based framework used on many sites.

 

Usually when we declare a new row we write

<div class="row">
    //...
</div>

 

Now we want that to be shortened to

<row>
    //...
</row>

 

 

We do this is by creating a new C# class that derives from TagHelper

 

 

Fine tuning:

That's crazy because ASP.NET 5 has little to no Overhead. It's very lean and modular. However we can help the server to tell him what and what not to process to save some resources.

 

Option 1: Tell the server what not to process.:

<!a href="http://google.com">Porn Machine</!a>

 

Option 2: Or you can tell the server what to process (opposite)

Add this line to your _GlobalImports.cshtml (Beta5+ it's renamed to _ViewImports.cshtml)

@tagHelperPrefix "do-"

 Now we can tell the server what to process:

<do-a asp-controller="Home" asp-action="About">About us</do-a>

 



Mahmut Jomaa is a Software Engineer from Germany.

Currently he attends university to gain more knowledge in Computer Science.


Security code Refresh