SoFunction
Updated on 2025-04-07

Usage of TagHelper in Core MVC

1. What is Tag Helper

Tag Assistant is the server code that can participate in creating and rendering HTML elements in a Razor file. For example, the built-in ImageTagHelper can append the version number to the image name. Whenever an image is changed, the server generates a new unique version of the image, so it is guaranteed that the client gets the current image (rather than an outdated cached image). The built-in tag assistant is mostly used for common tasks such as creating forms, linking and loading resources. Tag helpers are defined in C# and they locate HTML elements based on element names, attribute names, or parent tags. For example, when applying the LabelTagHelper feature, the built-in LabelTagHelper can reduce the display conversion between HTML and C# in the Razor view.

Differences between tag assistant and HTML assistant:

* Tag Assistant provides an HTML-friendly development experience

In most cases, the Razor tag using the tag assistant looks like standard HTML. If you are familiar with HTML/CSS/Javascript, you can edit Razor directly without learning C# syntax.

* Rich IntelliSence environment for creating HTML and Razor tags

HTML Helper is a method to create tags on the server side in the Razor view. IntelliSense supports Tag HelpersIntelliSense interpreting environments. Even developers with experience in Razor C# syntax use Tag Helpers, it is more efficient than using C# Razor tags.

There is also a more efficient way to generate more powerful, reliable and maintainable code using the information provided on the server. For example, when you update an image, you actually change the image name when you change the image. For performance reasons, the cache should be cleared unless the image name is changed. The built-in ImageTagHelper can automatically change the image name, and ImageTagHelper can append the version number to the image name, so whenever an image is changed, the server will automatically generate a new unique version for the image. Ensure that the client can obtain the current image.

Most built-in tag assistants point to existing HTML elements and provide server-side attributes to the elements. For example, many of the <input> elements used in the Views/Account folder contain the asp-for attribute, which extracts the name of the specified model attribute into the rendered HTML. The asp-for attribute has 2 For attributes provided in LabelTagHelper.

*Manage tag assistant scope

The tag assistant range is controlled by @addTagHelper, @removeTagHelper and "!" for the combination of strings.

@addTagHelper Makes the tag assistant available. Default _ViewImports.cshtml file:

@using MVCTest
@using 
@addTagHelper *, 
@addTagHelper ",MVCTest"

The above code uses wildcard syntax (" * ") to specify that all tag assistants in the assembly will be available for each view file in the Views directory or subdirectory. The first parameter after @addTagHelper specifies the tag assistant to be loaded, and the second parameter "" specifies the assembly containing the tag assistant.   is an assembly of the built-in Core tag assistant.

If your project contains an EmailTagHelper with the default namespace(), you can provide a fully qualified name (FQN) of the tag assistant:

@using MVCTest
@using 
@addTagHelper *, 
@addTagHelper  “,AuthoringTagHelpers”

To use FQN to add a tag assistant to the view, add FQN () first, and then add the assembly name (AuthoringTagHelpers). Most developers prefer to use the "*" wildcard syntax. Wildcard syntax allows the insertion of wildcard "*" as a suffix in FQN. For example:

@addTagHelper  “ *,AuthoringTagHelpers”
@addTagHelper  “ *,AuthoringTagHelpers”

If you want to select Enable to display the tag assistant to only those views, you can use the @addTagHelper directive in a specific view.

* @removeTagHelper Delete Tag Assistant

@removeTagHelper has the same two parameters as @addTagHelper , which removes the tag assistant that was added before. For example, @removeTagHelper applied to a specific view removes the specified tag assistant from the view. Use @removeTagHelper in the Views/Floder/_ViewImports.cshtml file to delete the specified tag assistant from all views of the Floder.

*Use _ViewImports.cshtml File control tag assistant scope

You can add    to any view folder and the driving engine adds instructions from the   file to the instructions contained in the Views/ file. If you add an empty file to the Home view, nothing will change because the file is overlaid. Any @addTagHelper directive added to the Views/Home/ file will be used by these tag assistants to appear only in the Home folder.

*Open the individual elements

You can use the tag assistant to exit character (" ! ") to disable the tag assistant at the element level. For example, use the tag assistant exit character to disable mail verification in <span>:

<!span asp-validation-for="Email" class="text-danger"><!span>

The tag assistant exit character must be applied to the start and end tags. After adding the tag assistant exit character, the elements and tag assistant properties are no longer displayed in special fonts.

2. Use @tagHelperPrefix to make the tag assistant display use

The @tagHelperPrefix directive allows you to specify a tag prefix string to enable tag assistant support and enable tag assistant display. For example, the following code, the tag assistant prefix is ​​set to th: , so only elements with the prefix th: support Tag Helper (element special font that enables tag assistant). The <label> and <input> elements have the tag assistant prefix and the tag assistant is enabled, while the <sapn> element is not enabled:

<div class="form-group">
                <th:label asp-for="Id" class="control-label"></th:label>
                <th:input asp-for="Id" class="form-control" />
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>

The same hierarchical rules for @addTagHelper are also used for @tagHelperPrefix.

When creating a web application in VS, add "" to the file, which is the package that adds the Tag Helper tool.

Once you enter <l in the VS editor, Intelligent Perception will display the matching elements. Intelligent perception statements allow the statements for the selected value to be entered using the Tab key.

You can enter the CompleteWord shortcut key of VS (double quotes) in the property value (default is Ctrl+space). Now in C#, it is like a C# class. Intelligent perception displays all methods and properties of the page model, and can also help select CSS classes.

3. Comparison of Tag Helpers and HTML Helpers

The tag assistant is an HTML element attached to the Razor view, while the HTML assistant is a method call for HTML interspersed in the Razor view. The following Razor tag creates an HTML tag with the CSS class "caption":

@("FirstName", "First Name:", new {@class="caption"})

The @ symbol tells Razor that this is the beginning of the code. The next two parameters ("FirstName" and "First Name:") are strings, so IntelliSence does not help. The last parameter new {@class="caption"} is an anonymous object used to represent attributes. Because class is a keyword in C#, use the @ symbol to force C# to interpret @class= as a symbol.

Using LabelTagHelper, the same tag can be written as:

<label asp-for="FirstName" class="caption"></label>

With LabelTagHelper, Intelligent Perception will display the matching elements as long as you enter <l in VS.

The following code is the Razor view form part generated by the 4. MVC template in VS2015:

@using (())
{
    @()
    
    &lt;div class="form-horizontal"&gt;
        &lt;h4&gt;Modify information&lt;/h4&gt;
        &lt;hr /&gt;
        @(true, "", new { @class = "text-danger" })
        @(model =&gt; )
        @(model =&gt; )

        &lt;div class="form-group"&gt;
            @(model =&gt; , htmlAttributes: new { @class = "control-label col-md-2" })
            &lt;div class="col-md-10" style="padding-top:7px"&gt;
                @(model =&gt; , new { htmlAttributes = new { @class = "form-control" } })
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            @(model =&gt; , htmlAttributes: new { @class = "control-label col-md-2" })
            &lt;div class="col-md-10" style="padding-top:7px"&gt;
                @(model =&gt; , new { htmlAttributes = new { @class = "form-control" } })
            &lt;/div&gt;
        &lt;/div&gt;


        &lt;div class="form-group"&gt;
            &lt;div class="col-md-offset-2 col-md-10"&gt;
                &lt;input type="submit" value="save" class="btn btn-default" /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
}

Here is the code for the tag assistant form part of the Core MVC template:

<div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id" class="control-label"></label>
                <input asp-for="Id" class="form-control" />
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>

4. Comparison of tag assistant and WEB server controls

Web server controls are declared and called on the page. Tag assistants do not have elements associated with them, they simply participate in the presentation of elements and content.

Web server controls have a different life cycle, making it difficult to develop and debug.

Web server controls allow adding functionality to the client document object model (DOM) by using client space. Tag Assistant does not have DOM.

Web server controls include automatic browser detection, and the tag assistant cannot recognize the browser.

Multiple tag assistants can perform operations on the same element, but they are usually unable to write web server controls.

The tag assistant can modify the tags and contents of its scoped HTML elements, but does not directly modify any other content on the page.

Web server controls use type converters to convert strings into objects. With the tag assistant, they can work in C# without type conversion.

Web server controls are used to implement runtime and design-time behavior of components and controls. Includes base classes and interfaces for implementing attribute and class converters, bound to data sources and license components. Compared with the tag assistant, it is usually derived from TagHelper. The TagHelper base class only exposes two methods: Process  and ProcessAsync.

5. Custom Tag Assistant

1. Write an email tag assistant

The tag assistant is any class that implements the ITagHelper interface. However, when writing a tag assistant, you usually start with the TagHelper class, so that you can access the Process method.

First create a TagHelpers folder and add an EmailTagHelper class:

public class EmailTagHelper:TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
             = "a"; // Used to replace <email> with <a>        }
    }

Notice:

* The tag assistant uses the naming convention of using the target element name as the root class name (the TagHelper part in the out-of-class name). The final corresponding tag to EmailTagHelper is email

* The EmailTagHelper class must be derived from TagHelper, and the Process method must be rewrite.

* The context parameters of Process or ProcessAsync contain information related to the execution of the current HTML tag, and the output parameters contain the static HTML element rendering of the source code used to generate HTML tags and content.

The class name suffix does not have to be TagHelper, but it is recommended to add it.

The following is the email tag assistant in the project. In _ViewImports.cshtml, use addTagHelper to add the EmailTagHelper class:

@using MVCTest
@using 
@addTagHelper *, 
@addTagHelper ",MVCTest"

The first string after @addTagHelper indicates the tag assistant to be loaded, and the second string indicates the assembly where the tag assistant is located. Add tags to the Views/Home/ file:

@{
    ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<address>
    One Microsoft Way<br />
    Redmond, WA 98052-6399<br />
    <abbr title="Phone">P:</abbr>
    425.555.0100
</address>

<address>
    <strong>Support:</strong> <email>Support</email><br />
    <strong>Marketing:</strong> <email>Marketing</email>
</address>

Run the program and use the browser to view the HTML code, you can see that the email tags are replaced with link tags. But there is no href attribute.

2. Improve email tag assistant

Update the EmailTagHelper class:

public class EmailTagHelper:TagHelper
    {
        private const string EmailDomain = "";
        public string MailTo { get; set; } //Add nail-to attribute, such as <email mail-to="..." />        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
             = "a"; // Used to replace <email> with <a>            var address = MailTo + "@" + EmailDomain;
            ("href","mailto:"+address);
            (address); //Set the content of the tag assistant        }
    }

Update Views/Home/  , plus the mail-to attribute:

@{
    ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<address>
    One Microsoft Way<br />
    Redmond, WA 98052-6399<br />
    <abbr title="Phone">P:</abbr>
    425.555.0100
</address>

<address>
    <strong>Support:</strong> <email mail-to="Support">Support</email><br />
    <strong>Marketing:</strong> <email mail-to="Marketing">Marketing</email>
</address>

Name the class names and attribute names of tag assistants in the form of Pascal will be translated into their lowercase kebab form. Therefore, use the MailTo property, and use <eamil mail-to="value" />.

3. Asynchronous Tag Assistant

Update EmailTagHelper:

public class EmailTagHelper:TagHelper
    {
        private const string EmailDomain = "";

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
             = "a"; // Used to replace <email> with <a>            var content = await ();
            var target  = () + "@" + EmailDomain;
            ("href", "mailto:" + target);
            (target);
        }
    }

Views/Home/ :

@{
    ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<address>
    One Microsoft Way<br />
    Redmond, WA 98052-6399<br />
    <abbr title="Phone">P:</abbr>
    425.555.0100
</address>

<address>
    <strong>Support:</strong> <email>Support</email><br />
    <strong>Marketing:</strong> <email>Marketing</email>
</address>

This is all about this article about the usage of Core MVC TagHelper. I hope it will be helpful to everyone's learning and I hope everyone will support me more.