ASP.MVC 6 Features - All New Tag Helpers

We are using HTML helpers in our view pages extensively while building apps in MVC untill now. The main disadavantage of this is that it follows server side syntax and it's mix and match with html code in the page. It makes the maintainablity a tedious one and also readablity is affected.

@Html.Label("Name","Name")

In ASP.NET MVC 6 we have the tag helpers which helps you achieve the same thing but this time we are writing using the HTML markup. So the equivalent code for above statment in MVC 6 will be

<label asp-for="Name"></label>

will generate the following HTML when rendered in browser

<label for="Email">Email</label>

Here the asp-for attributes extracts the display name attribute from the specified model property and displays it as the label for the control.

Let's add a class to the above control and see the difference between HTML Helpers and Tag Helpers

HTML Helper

@Html.Label("Name","Name", new {@class="label-caption"})

Tag Helper 

<label class ="label-caption" asp-for="Email">Email</label>

Generated HTML

<input name="Name" class="label-caption" id="Name" type="text" value="">

If a UI designer looks at both these codes, he will definetely prefer the latter one because he can easily relate that syntax to his acquired skills which is HTML and javascript. The HTML helper code is much like C# syntax and it will be difficult for them to easily understand what it does and how it's being done.

Intellisense is also available inside the tags for HTML/CSS attritutes as well as for the Tag Helper targeted attributes.

HTML/css Attributes auto completion

Model properties available in Intellisense list

Visual Studio is very intelligent in identifying a tag helper from the normal HTML control by giving different colors for each statement. For example if we are using <label> control for displaying the caption. If the label tag contains asp-for attribute then it's a tag helper and the it will have white color for the attribute value and the rest will be dark green.

If it doesn't have a asp-for attribute then it will be treated as a normal <label> tag  and color of the tag will be blue, attributes will have light blue color and values of attributes will be in ash color.

If you are using white theme, then the colors will be different. But you will be able to distingush it visually.


No Comments

Add a Comment