outline

ASP.net core tag helpers usage cheat sheet

Tag helpers represent the way to create custom html elements in asp.net core's Razor templating engine they replace the old and deprecated Html Helper facility.

This document is a cheat sheet that outlines briefly the key-points of using existing tag helpers will not be very helpful if you need to understand tag helpers from scratch

A lot of introductory resources are available online if you are not familiar with the concept. The following articles are a good starting point:

Keypoints

  • Tag Helpers substitute markup in cshtml files with standard html markup:
    <hello-world></hello-world> turns to <p>Hello World!</p>
  • Built-in tag helpers are available under the Microsoft.AspNetCore.Mvc.TagHelpers assembly
  • Substitution can be activated by custom html tag name, custom html attribute and standard html elements name: <label asp-for="Email"></label>

Usage

  • Tag helpers need to be included in cshtml files by using the @addTagHelper directive:
  • The default asp.net core project template includes @addTagHelper in View/Shared/_ViewImports.cshtml:
  • There is a variety of useful built-in tag helpers (cache, img, ...)
  • Once included tag helpers can be used in cshtml files and IntelliSense support is available in visual studio
  • Some tag helpers provide custom attributes:
    <hello-world name="Ali"></hello-world>
  • Some tag helpers can accept a C# expression:
    <hello-world name="new SomeModel() { Id=2149 }"></hello-world>
  • It is possible to use standard html attributes:
    <hello-world id="the-hello-world" class="a-hello-world"></hello-world> turns to <p id="the-hello-world" class="a-hello-world">Hello World!</p>
  • It is possible to remove (uninclude) tag helpers from a specific view by using the @removeTagHelper directive:
    @removeTagHelper img, TechDominator.TagHelpersAssembly
  • It is possible to disable tag helper activation for specific element by using the ! operator:
    <!hello-world></!hello-world> turns to <hello-world></hello-world>
  • Some tag helpers can accept content and even nested elements which can be tag helpers as well: