Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the tag TagHelper in ASP.NET Core MVC

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use the tag TagHelper in ASP.NET Core MVC". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the tag TagHelper in ASP.NET Core MVC.

1. What is the tag Assistant Tag Helper

The tag helper is that server-side code can participate in the creation and rendering of HTML elements in Razor files. For example, the built-in ImageTagHelper can append the version number to the image name. Whenever you change an image, the server generates a new and unique version of the image, so you can ensure that the client gets the current image (rather than the 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 locate HTML elements based on element names, attribute names, or parent tags. For example, when the LabelTagHelper feature is applied, 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 a HTML-friendly development experience

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

* Rich IntelliSence environment for creating HTML and Razor tags

HTML Helper is the previous way to create tags on the server side in the Razor view. IntelliSense supports Tag HelpersIntelliSense interpretation of the environment. Even developers with Razor C # syntax experience using Tag Helpers are more efficient than using C # Razor tags.

There is also a more efficient way to generate more powerful, reliable, and maintainable code using all the information provided on the server. For example, the image name was changed when the image was actually changed when the image was updated. For performance reasons, the cache should be cleared unless the image name is changed. The built-in ImageTagHelper automatically changes the image name, and ImageTagHelper appends the version number to the image name, so whenever you change the image, the server automatically generates a new and unique version of the image. Ensure that the client can get the current image.

Most of the built-in tag helpers point to existing HTML elements and provide server-side attributes for the element. For example, many of the 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 property is provided by the For property in 2 LabelTagHelper.

* manage the scope of the tag assistant

Tag helper ranges from @ addTagHelper, @ removeTagHelper and "!" To deduce the combination control of strings.

@ addTagHelper makes the tag assistant available. Default _ ViewImports.cshtml file:

@ using MVCTest@using MVCTest.Models@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers@addTagHelper "MVCTest.TagHelpers.EmailTagHelper,MVCTest"

The above code uses wildcard syntax ("*") to specify that all tag helpers in the assembly will be available for each view file in the Views directory or subdirectory. The first parameter after @ addTagHelper specifies the tag helper to load, and the second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the assembly that contains the tag helper. Microsoft.AspNetCore.Mvc.TagHelpers is the assembly of the built-in ASP.NET Core tag helper.

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

@ using MVCTest@using MVCTest.Models@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers@addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper,AuthoringTagHelpers"

To add the tag helper to the view using FQN, add FQN (AuthoringTagHelpers.TagHelpers.EmailTagHelper) before adding the assembly name (AuthoringTagHelpers). Most developers like to use the "*" wildcard syntax. Wildcard syntax allows you to insert the wildcard "*" as a suffix in FQN. For example:

@ addTagHelper "AuthoringTagHelpers.TagHelpers.E *, AuthoringTagHelpers" @ addTagHelper "AuthoringTagHelpers.TagHelpers.Email *, AuthoringTagHelpers"

If you want to choose to enable the tag assistant to be displayed only to 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 previously added tag helper. For example, the @ removeTagHelper applied to a specific view removes the specified label helper from the view. Use @ removeTagHelper in the Views/Floder/_ViewImports.cshtml file to remove the specified tag helper from all views in Floder.

* use the _ ViewImports.cshtml file to control the scope of the tag assistant

You can add ViewImports.cshtml to any view folder and drive into the engine to add instructions from the ViewImports.cshtml file to the instructions contained in the Views/ViewImports.cshtml file. If you add an empty ViewImports.cshtml file to the Home view, there will be no change because the ViewImports.cshtml file is superimposed. Any @ addTagHelper directive added to the Views/Home/ViewImports.cshtml file will use these tag helpers to appear only in the Home folder.

* choose to exit individual elements

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

You must use the tag assistant exit symbol for the start and end tags. After you add a tag assistant exit symbol, the element and tag assistant attributes are no longer displayed in a special font.

two。 Use @ tagHelperPrefix to make the tag assistant display using the

The @ tagHelperPrefix directive allows you to specify a tag prefix string to enable tag assistant support and to make the tag assistant display and use. For example, in the following code, the tag helper prefix is set to th:, so only elements with the prefix th: support Tag Helper (special fonts for elements that enable the tag helper) are used. And elements have a tag helper prefix and the tag helper is enabled, but the element is not enabled:

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

When creating a web application in VS, add "Microsoft.AspNetCore.Razor.Tool" to the project.json file, which is the package for adding the Tag Helper tool.

Enter model.Account @ Html.LabelFor (model = > model.Id, htmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayFor (model = > model.Id, new {htmlAttributes = new {@ class = "form-control"}}) @ Html.LabelFor (model = > model.Account) in the VS editor HtmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayFor (model = > model.Account, new {htmlAttributes = new {@ class = "form-control"}})}

The following is part of the code for the tag assistant form of the ASP.NET Core MVC template:

4. Comparison between label 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 rendering of elements and content.

Web server controls have a different lifecycle, which makes it difficult to develop and debug.

The Web server control allows you to add functionality to the client document object Model (DOM) by using the client space. The tag Assistant does not have a DOM.

The Web server control includes automatic browser detection, and the label assistant does not recognize the browser.

Multiple label assistants can perform operations on the same element, but it is usually not possible to write Web server controls.

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

Web server controls use type converters to convert strings to objects, and with a label assistant, you can work in C # without type conversion.

Web server controls use System.ComponentModel to implement the run-time and design-time behavior of components and controls. System.ComponentModel includes base classes and interfaces for implementing properties and class converters, binding to data sources and licensed components. Compared to the tag helper, usually derived from the TagHelper,TagHelper base class, only Process and ProcessAsync methods are exposed.

5. Custom tag Assistant 1. Write an email tag assistant

The tag helper is any class that implements the ITagHelper interface. However, when writing a tag helper, 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) {output.TagName = "a"; / / used to replace with}}

Note:

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

* the EmailTagHelper class needs to be derived from TagHelper, overriding the Process method

* the context parameters of Process or ProcessAsync contain information related to the current HTML tag execution, 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.

Let's use the email tag assistant in the project. In _ ViewImports.cshtml, add the EmailTagHelper class using addTagHelper:

@ using MVCTest@using MVCTest.Models@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers@addTagHelper "MVCTest.TagHelpers.EmailTagHelper,MVCTest"

The first string after @ addTagHelper indicates the tag helper to load, and the second string indicates the assembly in which the tag helper is located, adding tags to the Views/Home/Contact.cshtml file:

@ {ViewData ["Title"] = "Contact";} @ ViewData ["Title"] @ ViewData ["Message"] One Microsoft Way Redmond, WA 98052-6399 P: 425.555.0100 Support: Support Marketing: Marketing

Running the program and using a browser to view the HTML code, you can see that the email tags have been replaced with link tags. But there is no href attribute.

two。 Perfect email tag Assistant

Update the EmailTagHelper class:

Public class EmailTagHelper:TagHelper {private const string EmailDomain = "contoso.com"; public string MailTo {get; set;} / / add nail-to attributes, such as public override void Process (TagHelperContext context, TagHelperOutput output) {output.TagName = "a"; / / used to replace with var address = MailTo + "@" + EmailDomain Output.Attributes.SetAttribute ("href", "mailto:" + address); output.Content.SetContent (address); / / set the content of the tagging assistant}}

Update Views/Home/Contact.cshtml with the mail-to attribute:

@ {ViewData ["Title"] = "Contact";} @ ViewData ["Title"] @ ViewData ["Message"] One Microsoft Way Redmond, WA 98052-6399 P: 425.555.0100 Support: Support Marketing: Marketing

Naming the tag helper's class and attribute names in Pascal will be translated into their lowercase kebab form. So use the MailTo property, and use the.

3. Asynchronous tag Assistant

Update EmailTagHelper:

Public class EmailTagHelper:TagHelper {private const string EmailDomain = "contoso.com"; public override async Task ProcessAsync (TagHelperContext context, TagHelperOutput output) {output.TagName = "a"; / / used to replace with var content = await output.GetChildContentAsync (); var target = content.GetContent () + "@" + EmailDomain; output.Attributes.SetAttribute ("href", "mailto:" + target) Output.Content.SetContent (target);}}

Views/Home/Contact.cshtml:

@ {ViewData ["Title"] = "Contact";} @ ViewData ["Title"] @ ViewData ["Message"] One Microsoft Way Redmond, WA 98052-6399 P: 425.555.0100 Support: Support Marketing: Marketing so far, I believe you have a deeper understanding of "how to use the tag TagHelper in ASP.NET Core MVC". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report