A feature introduced in MVC 6 is Tag Helpers. Similar to HtmlHelpers they are designed to simplify the work required to author views. HtmlHelpers are C# methods that are placed within views to generate html. Typically the methods targeted common existing html elements and perform their html generation out of sight of the view.
Tag Helpers introduce a syntax, that augment html with special tag helper attributes, that is more familiar to someone use to writing pure html than calling C# methods.
Using HtmlHelpers with Razor:
<div>
@Html.LabelFor(x => x.Name)
@Html.TextBoxFor(x => x.Name, new { @class = "input-small" })
@Html.ValidationMessageFor(x => x.Name)
</div>
Using Tag Helpers:
<div>
<label asp-for="Name"></label>
<input type="text" asp-for="Name" class="input-small" />
<span asp-validation-for="Name"></span>
</div>
Tag Helpers can be more readable especially if we are using a HtmlHelper with a lot of parameters including anonymous classes.
How To Enable Tag Helpers:
To enable Tag Helpers you need to install the TagHelpers nuget package.
Install-Package Microsoft.AspNet.Mvc.TagHelpers
Other Tag Helpers:
MVC 6 comes with a number of Tag Helpers and also provides the functionality to build your own. Some inbuilt Tag Helpers include:
Anchor Tag Helper
Similar to Html.Action()
, used to generate links to a controller action.
<a asp-action="Index" asp-controller="Home">Homepage</a>
Image Tag Helper
Rendering of an image tag with a query string value that changes as the content of the image changes forcing the browser to download the image if it changes.
<img src="~/content/images/banner.jpg" asp-append-version="true" />
Environment Tag Helper
The environment Tag Helper allows you to include markup based on the current Environment ASPNET_ENV value.
<environment names="Development">
<p>This is the development environment.</p>
</environment>
<environment names="Production">
<p>This is the production environment.</p>
</environment>
Cache Tag Helper
By wrapping content within a cache Tag Helper the contents will be cached in memory. There are three options for expiry expires-after
, expires-on
, expires-sliding
. If no expiry option is provided the cache will last as long as the memory cache decides to hold onto it (normally for the lifetime of the application). There are also options for the cache to be varied by different properties.
<cache expires-after="@TimeSpan.FromSeconds(5)">
Last updated @DateTime.Now.ToLongTimeString()
</cache>