ASP.NET Core 1.0 MVC TagHelper

Tag Helpers is a special feature to enable Server side code to create, update and render HTML in view file. They are said to be evaluations of HTML Helpers. Although, HTML Helpers exist, yet Tag Helpers are very popular as they are just additional attributes in existing HTML elements and are very easy for UI designers or front stack developers to understand.

Tag Helpers are attached to HTML tags without effecting raw view. On the other hand, HTML Helpers are the methods, which are called to yield required HTML. Furthermore, Tag Helper is powered by IntelliSense in Visual Studio, while HTML Helper does not support IntelliSense much. In a nutshell, Tag Helpers are efficient, easy to code and make code cleaner with respect to HTML Helper along with many features out of the box. Generally, all Tag Helpers use "asp-" attributes to specify the special values. For example-

  • asp-controller is used to specify the controller to be used.
  • asp-action is used to specify the action method to be used.
  • asp-area is used to specify the area to be used.
  • asp-for is used to specify the property to be used. Generally, this property is bond to specified control. 
  • asp-route is used to specify the named route instead of the controller and action method.
  • asp-validation-for is used to specify the property to be validated.
  • asp-validation-summary is used to specify the mode of validation summary to be used.
  • asp-antiforgery is used to enable or disable antiforgery.
  • asp-append-version is used to add the version number to the resource, so if there is any change in the resource, the version number also changes. It ensures that in case of any change, one resource is not used from cache.

ASP.NET Core provides a set of predefined Tag Helpers in Microsoft.AspNetCore.Mvc.TagHelpers. This namespace provides important Tag Helpers, as shown below.

  • AnchorTagHelper
  • FormTagHelper
  • ImageTagHelper
  • InputTagHelper
  • LabelTagHelper
  • LinkTagHelper
  • OptionTagHelper
  • ScriptTagHelper
  • SelectTagHelper
  • TextAreaTagHelper
  • ValidationMessageTagHelper
  • ValidationSummaryTagHelper
  • CacheTagHelper
  • DistributedCacheTagHelper
  • EnvironmentTagHelper

AnchorTagHelper

AnchorTagHelper is used with a tag. It allows the data element to map a tag through asp-area, asp-controller, asp-action, asp-route to specify the area, controller, action method and route. We can also pass the parameters asp-route- construct.

<a asp-controller="Contact" asp-action="GetContact" asp-route-id="1">Get Details</a>

FormTagHelper

FormTagHelper is used with the form tag. It allows us to specify the controller, action method. It also allows us to specify the route name instead of the controller and action. Furthermore, it provides services to handle cross-site request forgery. It is important to remember that on submit action, form uses name fields of inner objects to create the response body.

<form asp-controller="Contact" asp-action="CreateContact" asp-antiforgery="true" method="post">
...
</form>


ImageTagHelper

ImageTagHelper is used with img tag. It allows to specify asp-append-version, which is used to address the image cache problem.

<img asp-append-version="true" src="/logo.png" alt="My ORganization" />

InputTagHelper

InputTagHelper is used with the input tag. It allows the data element to map the input tag through asp-for attribute. The input tag type is decided through the data element type and data annotation. The data validation rules are applied through the data annotation.
 
For example, element data type Boolen will make type="checkbox", String will make type="text", DateTime will make type="datetime"and Byte, Integer, Single, Double will make type="number". Similarly data annotation EmailAddress will make type="email", Url will make type="url", HiddenInput will make type="hidden", Phone will make type="tel", Password will make type="password", Date will make type="date"and Time will make type="time".

<input asp-for="Name" class="form-control" />

LabelTagHelper

LabelTagHelper is used with label tag. It allows the data element to map the input tag through asp-for attribute. It uses Display data annotation value of the specified data element to display the label. If Display attribute has not been applied, the element name is used.

<label asp-for="Name" class="col-md-2 control-label"></label>

LinkTagHelper

LinkTagHelper is used with the link tag. It allows to control the link behavior. For example, specify and control the source and fallback source.

<link asp-append-version="true" /link>

OptionTagHelper

OptionTagHelper is used with the option tag in the select tag. It allows to manipulate the option elements individually by SelectTagHelper.

<select asp-for="Title" asp-items="Model.Titles"></select>

ScriptTagHelper

ScriptTagHelper is used with the script tag. It allows to control the script block behavior. For example, specify and control the source and fallback source.

<script asp-append-version="true">
...
</script>


SelectTagHelper

SelectTagHelper is used with the select tag. It allows the data element to be map with the select tag and option through asp-for and asp-items attributes, while asp-for is used to specify the selected value element and asp-items are used to specify the list to be bounded with the options. The data validation rules are applied through the data annotation.

<select asp-for="Title" asp-items="Model.Titles"></select>

TextAreaTagHelper

TextAreaTagHelper is used with the textarea tag. It allows the data element to be map with the textarea tag through asp-for attribute. The data validation rules are applied through data annotation.

<textarea asp-for="Description" rows="5" cols="30" />

ValidationMessageTagHelper

ValidationMessageTagHelper is used with the span tag. It allows the validation messages to be mapped to span tag through asp-validation-for attribute.

<span asp-validation-for="Name" class="text-danger" />

ValidationSummaryTagHelper

ValidationSummaryTagHelper is used with the div tag. It allows all the validation messages mapped to div tag filtered through asp-validation-summary attribute. The possible values for asp-validation-summary are All, ModelOnly, None.

<div asp-validation-summary="ModelOnly" class="text-danger"></div>

CacheTagHelper

CacheTagHelper is used to cache the content for any section of a view. It is not applied to any standard HTML tags, rather than, it is a Server side control. It uses the MemoryCache to store.

Please refer to In Memory Caching for more details. It allows us to control cache expiry as per the requirement with the attributes, given below.

  • expires attribute allow to specify

    • Time interval after which the cached data will expire, using expires-after.
    • Time interval after which the cached data will expire, if not used using expires-sliding.
    • Fixed time interval on which the cached data will expire, using expires-on.

      <cache expires-after="@TimeSpan.FromSeconds(100)">
      ...
      </cache>

  • vary-by attribute allows to specify the cache data

    • Based on some key or model data, using vary-by.
    • Based on the user, using vary-by-user.
    • Based on the cookie, using vary-by-cookie.
    • Based on some header value, using vary-by-header
    • Based on some query string attribute, using vary-by-query.
    • Based on route, using vary-by-route.

      <cache vary-by-user="true">
      ...
      </cache>

  • Priority allows us to specify the priority of the cached content. When the system runs out of memory, it starts clearing the cached contents. In such a case, the items are cleared priority wise. We use Microsoft.Extensions.Caching.Memory.CacheItemPriority to specify the priority.

    <cache priority="@CacheItemPriority.Low">
    ...
    </cache>

  • We can use different attributes together to have a mixed mode as per our requirements. It is important to remember that there will be a cached copy for each combination and it can lead to use a huge memory.

    <cache expires-sliding="@TimeSpan.FromSeconds(100)" vary-by-user="true" priority="@CacheItemPriority.Low">
    ...
    </cache>

DistributedCacheTagHelper

DistributedCacheTagHelper is used to cache the content to the distributed cache Servers. It is very useful, when we want to handle a large amount of content or want to ensure that the cached data is even available, if the Web Application is restarted. There are a few requirements for the distributed cache.

It is our responsibility to define Unique Cache Key, else the content will be overwritten.

This distributed cache Service will be registered through Startup.ConfigureServices. If we do not configure any distributed cache Server , ASP.NET Core will use the default Memory Cache. We can use SqlServerCache or any other Cache like Radis Cache, as per the requirements. 

<distributed-cache name="UniqueCacheKey">
...
</distributed-cache>


EnvironmentTagHelper

EnvironmentTagHelper is a Server side Tag Helper, which is used to specify different HTML handling to be used for the different environment. It becomes very handy, when we have to specify the different URL's for the links and scripts for the different environment. 
  1. <environment names="Development">  
  2.     <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />  
  3.     <link rel="stylesheet" href="~/css/site.css" /> </environment>  
  4. <environment names="Staging,Production">  
  5.     <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />  
  6.     <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" /> </environment>