Tag Helpers is a new feature introduced in Asp.Net MVC Core to assist in generation of HTML elements in View. It is a feature of Razor View engine and are C# classes that participate in view generation by manipulating the HTML elements. By using Tag helpers, we can add additional attributes to HTML elements, change the content or replace them entirely. You can compare Tag Helpers with HTML helpers in Asp.Net MVC which are used to generate HTML elements in razor view page. For example, consider the below HTML helper,
@Html.TextBoxFor(model => model.Title, new { @class = "form-control", placeholder = "Enter Title" })
The same can be represented using Tag Helpers as,
<input asp-for="Title" placeholder="Enter Title" class="form-control" />
Both of the above methods produce same HTML output.
<input placeholder="Enter Title" class="form-control" id="Title" name="Title" value="" type="text">
When you compare both the representation, you can understand that using Tag Helpers highly simplify writing a view code.
Advantages of Tag Helpers
Tag Helpers helps to write MVC View code in HTML representation as opposed to HTML helpers which uses C# syntax. Anyone who knows HTML, for instance, a UI designer can understand the view code easily when using Tag Helpers. So, having said this, though in many cases we can replace HTML helper methods with Tag Helpers, it is not introduced to replace HTML helpers and not every HTML helpers have an alternate in Tag Helpers. So, we will be using Tag Helpers primarily but use HTML helpers at places when we don’t find a suitable tag helpers.
Tag Helpers also obey the metadata information set using Data Annotation in the view models and models. As seen in above example, the tag helpers will not replace any real html attributes (class, placeholder) already attached with HTML elements. So, it adds some additional functionality to a HTML element that increases the developer productivity with better readability and easy maintenance.
The other advantage of Tag Helpers over HTML helpers are, Visual Studio provides better intellisense support to build the HTML elements with Tag Helpers.
Note – For Visual Studio 2017, we need to install the Visual Studio 2017 extension Razor Language Services to get the Tag Helpers intellisense support.
In visual studio, the html elements that has tag helpers support will display in violet font as seen below. The form, label, input, span elements with Tag Helper support are separately identified by the font colour whereas the plain HTML element like h4, hr, div elements are usually themed.
In one way, we can say Tag helpers are represented similar to AngularJs directives which provides better HTML code readability when compared to HTML helpers.
The Tag Helpers support is added to view pages from _ViewImports.cshml using @addTagHelper statement.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
The above line includes all the Tag Helpers defined in the assembly Microsoft.AspNetCore.Mvc.TagHelpers. The wild card * denotes to include all Tag Helper classes under this assembly to be visible to the views.
Moving forward, let’s see some of the commonly used Tag Helpers in Asp.Net Core MVC.
Input Tag Helpers
The input tag helpers helps us to add HTML fragments to the HTML input elements from the razor view page. The below input element has tag helper support added with asp-for attribute.
<input asp-for="Title" />
Most of the inbuilt tag helpers start with word asp-[attribute name] syntax. In HTML helpers, the models are generally binded with elements with lambda expression m=>m.Title but in case of tag helpers the attribute asp-for=Title will automatically bind with Model.Title view model property. It is because the asp-for takes a ModelExpression parameter value and therefore asp-for="Title" will become m =>m.Title during code generation.
As we know, the input elements has many type attribute values like text, datetime, number, checkbox, etc. The input Tag Helper decides the appropriate type based on the type of the property defined in view model. For example, string will be mapped to text type and int, double, single will be mapped to number and so datetime type. If there is a data annotation attribute set in view model, then type is inferred from the data notation attribute value. For example, when a view model property like Password is set [DataType(DataType.Password)] then tag helper will make the type property as type=”password”.
The tag helper generates the id and name attributes for the input html elements by itself.
Note - The Label, TextArea tag helpers work similar to input tag helpers.
Form Tag Helpers
The form tag helper, for example,
<form asp-controller="Account" asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal">
-
Generates a form element with form action url created from asp-controller & asp-action attributes. It also generates request verification token to prevent XSRF/CSRF attach when [ValidateAntiForgeryToken] attribute is attached with the action method.
-
The asp-route-returnurl adds a route value parameter for redirection. We can add a route parameter with syntax asp-route-[parameter] = [value]
Validation Tag Helpers
There are 2 tag helpers for validation, Validation Message Tag Helper and Validation Summary Tag Helper.
-
A Validation Message Tag Helper is used to display field level error message adjacent to the input element. It has asp-validation-for attribute to display error message specific to the model field in the attribute value in a span tag.
<span asp-validation-for="Email" class="text-danger"></span>
The above tag helper outputs the below html span elements with HTML 5 attributes data-valmsg-for and data-valmsg-replace like below.
<span class="text-danger field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
-
Used to display summary of all errors in the form. The Validation Summary Tag Helper will help to add a validation summary div element with asp-validation-summary attribute.
<div asp-validation-summary="All" class="text-danger"></div>
Environment Tag Helpers
The environment tag helpers are another very useful elements to add scripts and styles based on the environments the application is deployed.
<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.7/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>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
</environment>
The environment name Development, Staging, Production can be set the webserver environment variables. In Visual Studio 2017, you can find in project properties > Debug tab as seen below.
This tag helpers will emit the style sheets and script files based on the ASPNETCORE_ENVIRONMENT value set for the site.
The script and link tag has a fall back mechanisms if in case the scripts and styles referred in CDN are not reachable/down using asp-fallback-src attribute.
We can also include files based on wildcard using asp-src-include attribute. The below tag helper will add all the scripts under the folder and sub folder of lib/jquery-validation/dist into the output page.
<script asp-src-include="~/lib/jquery-validation/dist/**/*.js"></script>
Cache Busting
The one major issue when linking a static resource like script, style sheets, images in web page is Caching. Whenever there are changes in these static files, it is very difficult to get the latest modified script or style sheet or image from server though we clear cache. To solve this issue, we will mostly rename the files to get the modified version all these days. Using tag helpers, the attribute asp-append-version="true" will append a version has a query string parameter which changes when the file is modified. Tag helpers usage below,
<img src="~/images/codedigestlogo.png" asp-append-version="true"/>
<script src="~/js/site.js" asp-append-version="true"></script>
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
Let’s see how to create a custom tag helper in next article. Happy Coding!!
Further Reading
- Read Difference Between Asp.Net and Asp.Net Core for a side by side difference.
- To know more about the new features in Asp.Net Core, read Breaking Changes and New Features of Asp.Net Core MVC.