Predefined Tag Helpers

In this lesson, we will learn how to use all ASP.NET Core Razor predefined tag helpers.

ASP.NET Core predefined tag helpers include tag helpers for enhancing links, caching view and page areas, improving image tags, script tags, and specifying different content in development and production. We will describe each of them in a dedicated section.

All predefined tag helpers are defined in the Microsoft.AspNetCore.Mvc.TagHelpers dll that is part of the .NET Core runtime. These tag helpers are automatically added in the _ViewImports.cshtml files that are created in the Views and Pages folders when an ASP.NET Core MVC /ASP.NET Core Pages project is generated either with Visual Studio or with the dotnet .NET Core SDK command-line tool.

The anchor tag helper

We have already seen how the anchor tag helper works in the previous lesson. It is applied on every a tag having an asp-action attribute. Together with the asp-action and asp-controller attributes it may also have other attributes for specifying all parameters of the routing rule. These attributes have names like asp-route-{paramater name}. Thus, for instance, if we are targeting the Detail method of the HomeController, and if the routing rule that applies is "{controller=Home}/{action=Index}/{id?}", we may add an asp-route-id attribute to provide a value for the id parameter. Let’s look at the example below:

<a asp-controller="Home" asp-action="Detail" asp-route-id="3">Go to detail</a>

Which yields the HTML below:

<a href="/Home/Detail/3">Go to detail</a>

We may also add parameters that are not contained in the routing rule, in which case they are appended to the query string, as in the example below:

<a asp-controller="Home" asp-action="Detail" asp-route-id="3" asp-route-mode="short">Go to detail</a>

Which is rendered as:

<a href="/Home/Detail/3?node=short">Go to detail</a>

The image tag helper

The image tag helper applies to all img tags that have a src attribute and an asp-append-version attribute set to true. It doesn’t change the syntax of the img tag but adds a hash to the image URL query string to prevent cashing each time that the image changes as shown in the example below:

<img src="~/images/myImage.png" asp-append-version="true">

Which is rendered as:

<img src="/images/myImage.png?v=kM_dqr9NVtnMdsM2MUgdskVVFD">

The hash passed in the v query parameter is computed from the content of the image file, so it changes whenever the image changes and prevents the browser from rendering an old cached copy of the image.

The ~/ symbol is not a feature specific to the img tag helper but a Razor native feature we can use in all links contained in any tag of a Razor file. It stands for the application root. It is not equivalent to the HTML / symbol that stands for the root of the domain, because ASP.NET Core applications may be also placed in subfolders of the domain. So ~/, translates to / only when the application is placed in the domain root, otherwise it translates to /{application subfolder name}/.

The cache tag helper

The cache tag helper doesn’t modify an existing HTML tag but defines a completely new tag whose purpose is to cache the markup fragment contained between the cache open and closure tags.

Some of its attributes specify the duration of the cache:

  • expires-on accepts as value a DateTime value that specifies the exact time when the cache will expire.

  • expires-after a TimeSpan value that specifies the duration of the cache.

  • expires-sliding accepts a TimeSpan value. However, in this case, the cache expires when the cached content is not required for a time greater than the one specified by the TimeSpan.

Just one of the above attributes must be provided. It is also possible to disable caching by providing the attribute enabled="false".

The priority attribute determines which content is deleted first when the server is under memory pressure. The lowest priority cached content is always deleted first. It takes value from an enumeration containing: NeverRemove, High, Normal, Low. Normal is the default when the attribute is not specified.

All other attributes specify how many different copies of the same content to keep. Copies are indexed by some values. For instance, vary-by-query="v,mode" keeps a different copy of the content for each possible combination of values of the v and mode query string parameters. vary-by-route="id,key" do the same with two routing rule parameters named id and key.

Analogously, vary-by-header does the same with HTTP header values, while vary-by-cookie does the same with the values of the cookies whose names are specified inside the attribute.

vary-by-user uses different cache entries for different users. User is taken from the view/page Context.User property.

Finally, vary-by invalidates the content as soon as the value of vary-by changes. That value can be a string, an instance of a reference type, or an instance of a value type.

We will see an example of usage in the example at the end of this lesson.

The script tag helper

The script tag helper is executed each time a script tag contains both the asp-fallback-test and the asp-fallback-src attributes. Its purpose is to furnish an alternative download URL for the JavaScript URL specified in the usual src HTML attribute. More specifically, the JavaScript test specified in asp-fallback-test is executed, and in case it returns a JavaScript false, it is assumed that the download of the file specified in the src attribute failed, in which case the alternative URL specified in asp-fallback-src is tried. asp-fallback-test should contain something that evaluates to JavaScript true when the JavaScript file specified in src is successfully downloaded, such as the name of a function or the name of a global variable defined in the JavaScript file.

Its typical usage is to attempt loading a library from a CDN and falling back to a local copy if that CDN is not accessible. Attempting the usage of a script from a public CDN increases the probability of finding the content in the browser cache, but CDNs are not always accessible if the whole application is in a private network behind a firewall. The script tag helper allows trying a CDN without challenging the proper operation of the application.

The example below attempts to download jQuery from a CDN and then falls back on a local copy:

Get hands-on with 1400+ tech skills courses.