Basically tag helpers are classes which take part in processing (or creating) HTML elements inside Razor views. You can create C# code which will target desired HTML and produce desired output. For more throughtout explanation see Introduction to Tag Helpers in ASP.NET Core
Before we begin, make sure that your setup is correct. If your custom tag helpers are in Solution assembly then you need to add this line to your View/_ViewImports.cshtml file:
1
@addTagHelper*,Solution
How to add a HTML class attribute to all img elements by extending ImageTagHelper.#
If you use Bootstrap you may want to add img-fluid css class to images to automatically make all available images responsive.
We can achieve this by extending ImageTagHelper. Notice that we’re merging attributes, so our tag helper won’t override classes which are already present in the markup.
How to show number of allowed characters next to textarea by extending TextAreaTagHelper.#
Textarea has maxlength attribute, we’re going to display a message which’ll print it out with additional message. Note that we should use MaxLength attribute (from DataAnnotations) to check maximum length of sent data. I’ve ommited this for brevity.
BONUS: Did you know that you can add TagHelper to any HTML element?#
One of the great things about tag helpers is that you can make it work for any existing HTML tags. I’ve show you examples of extending existing tag helpers, but you can also create new tag helpers for any element.
As an example, you could create tag helper which would create sortable links for all table header cells (something linke <th asp-for="FirstName"></th>). Another example could be printout out “Empty” inside a table with no rows.