Sunday 9 October 2016

ASP.NET Core 1.0 MVC TagHelper

Tag Helpers are special feature to enable server side code to create, update and render HTML in view file. They are said to be evaluation of Html Helpers. Although, Html Helpers do 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 methods which are called to yield required HTML. Furthermore, Tag Helper has powered by IntelliSense in Visual Studio, while HTML Helper does not support IntelliSense much. In nutshell, Tag Helpers are efficient, easier to code and make code cleaner with respect to HTML Helper along with many features out of box. Generally all Tag Helpers has use "asp-" attributes to specify special values, for example:
  • asp-controller: is used to specify controller to be used.
  • asp-action: is used to specify action method to be used.
  • asp-area: is used to specify area to be used.
  • asp-for: is used to specify property to be used. Generally, this property is bond to specified control. 
  • asp-route: is used to specify named route instead of controller and action method. 
  • asp-validation-for: is used to specify property to be validated.
  • asp-validation-summary:is used to specify mode of validation summary to be used.
  • asp-antiforgery: is used to enable or disable antiforgery.
  • asp-append-version: is used to add version number to resource, so if there is any change in resource then version number is also changed. 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 us following important Tag Helpers:
  • AnchorTagHelper
  • FormTagHelper
  • ImageTagHelper
  • InputTagHelper
  • LabelTagHelper
  • LinkTagHelper
  • OptionTagHelper
  • ScriptTagHelper
  • SelectTagHelper
  • TextAreaTagHelper
  • ValidationMessageTagHelper
  • ValidationSummaryTagHelper
  • CacheTagHelper
  • DistributedCacheTagHelper
  • EnvironmentTagHelper

AnchorTagHelper

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

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

FormTagHelper

FormTagHelper is used with form tag. It allows to specify controller, action method. It also allows to specify route name instead of 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 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 image cache problem.

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

InputTagHelper

InputTagHelper is used with input tag. It allows data element to be mapped input tag through asp-for attribute. While input tag type is decided through data element type and data annotation. While data validation rules are applied through 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 data element to be mapped input tag through asp-for attribute. It uses Display data annotation value of specified data element to display label. If Display attribute has not been applied then element name is used.

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

LinkTagHelper

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

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

OptionTagHelper

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

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

ScriptTagHelper

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

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

SelectTagHelper

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

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

TextAreaTagHelper

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

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

ValidationMessageTagHelper

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

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

ValidationSummaryTagHelper

ValidationSummaryTagHelper is used with div tag. It allows all validation messages mapped to div tag filtered through asp-validation-summary attribute. Possible values for asp-validation-summary as: All, ModelOnly, None.

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

CacheTagHelper

CacheTagHelper is used to cache 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 MemoryCache to store.
Please refer to In Memory Caching for more details. It allows us to control cache expiry as per requirement with following attributes:

  • expires attribute allow to specify: 
    • Time interval after which cached data will expire using expires-after.
    • Time interval after which cached data will expire if not used using expires-sliding.
    • Fixed time interval on which cached data will expire using expires-on.

 <cache expires-after="@TimeSpan.FromSeconds(100)">
    ...
 </cache>
  • vary-by attribute allows to specify cache data:
    • Based on some key or model data using vary-by.
    • Based on user using vary-by-user
    • Based on 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 allow to specify priority of cached content. When system runs out of memory, it starts clearing cached contents, in such case items are cleared priority wise. We use Microsoft.Extensions.Caching.Memory.CacheItemPriority to specify priority.

 <cache priority="@CacheItemPriority.Low">
    ...
 </cache> 
  • We can use different attributes together to have mixed mode as per our requirements. But it is important to remember that there will be 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 content to distributed cache servers. It is very useful when we want to handle large amount of content or want to ensure that cached data is even available if web application is restarted. There are few requirements for distributed cache:
It is our responsibility to define Unique Cache Key, otherwise content will be overwritten.
This distributed cache service will be registered through Startup.ConfigureServices. If we do not configure any distributed cache server then ASP.NET Core will use default Memory Cache. We can use SqlServerCache or any other Cache like Radis Cache as per requirements. Please refer to Working with a Distributed Cache for more details.

 <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 different environment. It becomes very handy when we have to specify different URLs for links and scripts for different environments. Please refer to Working with Multiple Environments for more details. We can find related example in _Layout.cshtml.



 <environment names="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" />
 </environment>
 <environment names="Staging,Production">
    <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" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
 </environment>

4 comments:

  1. Nice article sir..i want develop new webapplication..Is asp.net core better choice or stick to old asp.net..Pls let me know

    ReplyDelete
  2. I may recommend to go for .NET Core. But take few preventives like third party dependencies as explained in following article:
    http://www.ijz.today/2016/08/what-is-net-core-10.html

    ReplyDelete
  3. Thnak you very much for quick response

    ReplyDelete
  4. Hướng dẫn cách trị trào ngược dạ dày thực quản bằng những loại thuốc trong tự nhiên mà hiệu quả nhất. NGoài ra bạn nên tham khảo thuốc chữa trào ngược dạ dày thực quản đặc trị của Tỳ Bách Thảo, đây là một trong những loại thuốc đông y chữa trào ngược thực quản hiệu quả nhất. Bệnh trào ngược dạ dày đang là một trong những mối đe dọa ảnh hưởng đến sức khỏe của con người toàn cầu.

    ReplyDelete