[asp.net core] Tag Helpers 简介(转)

时间:2022-09-13 14:10:07

原文地址

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

What are Tag Helpers?

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. For example, the built-in ImageTagHelper can append a version number to the image name. Whenever the image changes, the server generates a new unique version for the image, so clients are guaranteed to get the current image (instead of a stale cached image). There are many built-in Tag Helpers for common tasks - such as creating forms, links, loading assets and more - and even more available in public GitHub repositories and as NuGet packages. Tag Helpers are authored in C#, and they target HTML elements based on element name, attribute name, or parent tag. For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied. If you're familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views. Tag Helpers compared to HTML Helpers explains the differences in more detail.

What Tag Helpers provide

An HTML-friendly development experience For the most part, Razor markup using Tag Helpers looks like standard HTML. Front-end designers conversant with HTML/CSS/JavaScript can edit Razor without learning C# Razor syntax.

A rich IntelliSense environment for creating HTML and Razor markup This is in sharp contrast to HTML Helpers, the previous approach to server-side creation of markup in Razor views. Tag Helpers compared to HTML Helpers explains the differences in more detail. IntelliSense support for Tag Helpers explains the IntelliSense environment. Even developers experienced with Razor C# syntax are more productive using Tag Helpers than writing C# Razor markup

A way to make you more productive and able to produce more robust, reliable, and maintainable code using information only available on the server  For example, historically the mantra on updating images was to change the name of the image when you change the image. Images should be aggressively cached for performance reasons, and unless you change the name of an image, you risk clients getting a stale copy. Historically, after an image was edited, the name had to be changed and each reference to the image in the web app needed to be updated. Not only is this very labor intensive, it's also error prone (you could miss a reference, accidentally enter the wrong string, etc.) The built-in ImageTagHelper can do this for you automatically. The ImageTagHelper can append a version number to the image name, so whenever the image changes, the server automatically generates a new unique version for the image. Clients are guaranteed to get the current image. This robustness and labor savings comes essentially free by using the ImageTagHelper.

Most of the built-in Tag Helpers target existing HTML elements and provide server-side attributes for the element. For example, the <input> element used in many of the views in the Views/Account folder contains the asp-for attribute, which extracts the name of the specified model property into the rendered HTML. The following Razor markup:

<label asp-for="Email"></label>

Generates the following HTML:

<label for="Email">Email</label>

The asp-for attribute is made available by the For property in the LabelTagHelper. See Authoring Tag Helpers for more information.

Managing Tag Helper scope

Tag Helpers scope is controlled by a combination of @addTagHelper@removeTagHelper, and the "!" opt-out character.

@addTagHelper makes Tag Helpers available

If you create a new ASP.NET Core web app named AuthoringTagHelpers (with no authentication), the following Views/_ViewImports.cshtml file will be added to your project:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, AuthoringTagHelpers"

The @addTagHelper directive makes Tag Helpers available to the view. In this case, the view file is Views/_ViewImports.cshtml, which by default is inherited by all view files in the Views folder and sub-directories; making Tag Helpers available. The code above uses the wildcard syntax ("") to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the *Views directory or sub-directory. The first parameter after @addTagHelper specifies the Tag Helpers to load (we are using "" for all Tag Helpers), and the second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the assembly containing the Tag Helpers. *Microsoft.AspNetCore.Mvc.TagHelpers is the assembly for the built-in ASP.NET Core Tag Helpers.

To expose all of the Tag Helpers in this project (which creates an assembly named AuthoringTagHelpers), you would use the following:

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

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

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

To add a Tag Helper to a view using an FQN, you first add the FQN (AuthoringTagHelpers.TagHelpers.EmailTagHelper), and then the assembly name (AuthoringTagHelpers). Most developers prefer to use the "*" wildcard syntax. The wildcard syntax allows you to insert the wildcard character "*" as the suffix in an FQN. For example, any of the following directives will bring in the EmailTagHelper:

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

As mentioned previously, adding the @addTagHelper directive to the Views/_ViewImports.cshtml file makes the Tag Helper available to all view files in the Views directory and sub-directories. You can use the @addTagHelper directive in specific view files if you want to opt-in to exposing the Tag Helper to only those views.

@removeTagHelper removes Tag Helpers

The @removeTagHelper has the same two parameters as @addTagHelper, and it removes a Tag Helper that was previously added. For example, @removeTagHelper applied to a specific view removes the specified Tag Helper from the view. Using @removeTagHelper in a Views/Folder/_ViewImports.cshtml file removes the specified Tag Helper from all of the views in Folder.

Controlling Tag Helper scope with the _ViewImports.cshtml file

You can add a _ViewImports.cshtml to any view folder, and the view engine adds the directives from that _ViewImports.cshtml file to those contained in the Views/_ViewImports.cshtml file. If you added an empty Views/Home/_ViewImports.cshtml file for the Home views, there would be no change because the _ViewImports.cshtml file is additive. Any @addTagHelper directives you add to the Views/Home/_ViewImports.cshtml file (that are not in the default Views/_ViewImports.cshtml file) would expose those Tag Helpers to views only in the Home folder.

Opting out of individual elements

You can disable a Tag Helper at the element level with the Tag Helper opt-out character ("!"). For example, Email validation is disabled in the <span> with the Tag Helper opt-out character:

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

You must apply the Tag Helper opt-out character to the opening and closing tag. (The Visual Studio editor automatically adds the opt-out character to the closing tag when you add one to the opening tag). After you add the opt-out character, the element and Tag Helper attributes are no longer displayed in a distinctive font.

Using @tagHelperPrefix to make Tag Helper usage explicit

The @tagHelperPrefix directive allows you to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit. In the code image below, the Tag Helper prefix is set to th:, so only those elements using the prefix th: support Tag Helpers (Tag Helper-enabled elements have a distinctive font). The <label> and <input> elements have the Tag Helper prefix and are Tag Helper-enabled, while the <span> element does not.

[asp.net core] Tag Helpers 简介(转)

The same hierarchy rules that apply to @addTagHelper also apply to @tagHelperPrefix.

IntelliSense support for Tag Helpers

When you create a new ASP.NET web app in Visual Studio, it adds "Microsoft.AspNetCore.Razor.Tools" to the project.json file. This is the package that adds Tag Helper tooling.

Consider writing an HTML <label> element. As soon as you enter <l in the Visual Studio editor, IntelliSense displays matching elements:

[asp.net core] Tag Helpers 简介(转)

Not only do you get HTML help, but the icon (the "@" symbol with "<>" under it).

[asp.net core] Tag Helpers 简介(转)

identifies the element as targeted by Tag Helpers. Pure HTML elements (such as the fieldset) display the "<>"icon.+

A pure HTML <label> tag displays the HTML tag (with the default Visual Studio color theme) in a brown font, the attributes in red, and the attribute values in blue.

[asp.net core] Tag Helpers 简介(转)

After you enter <label, IntelliSense lists the available HTML/CSS attributes and the Tag Helper-targeted attributes:

[asp.net core] Tag Helpers 简介(转)

IntelliSense statement completion allows you to enter the tab key to complete the statement with the selected value:

[asp.net core] Tag Helpers 简介(转)

As soon as a Tag Helper attribute is entered, the tag and attribute fonts change. Using the default Visual Studio "Blue" or "Light" color theme, the font is bold purple. If you're using the "Dark" theme the font is bold teal. The images in this document were taken using the default theme.

[asp.net core] Tag Helpers 简介(转)

You can enter the Visual Studio CompleteWord shortcut (Ctrl +spacebar is the default) inside the double quotes (""), and you are now in C#, just like you would be in a C# class. IntelliSense displays all the methods and properties on the page model. The methods and properties are available because the property type is ModelExpression. In the image below, I'm editing the Register view, so the RegisterViewModel is available.

[asp.net core] Tag Helpers 简介(转)

IntelliSense lists the properties and methods available to the model on the page. The rich IntelliSense environment helps you select the CSS class:

[asp.net core] Tag Helpers 简介(转)

[asp.net core] Tag Helpers 简介(转)

Tag Helpers compared to HTML Helpers

Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as methods interspersed with HTML in Razor views. Consider the following Razor markup, which creates an HTML label with the CSS class "caption":

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

The at (@) symbol tells Razor this is the start of code. The next two parameters ("FirstName" and "First Name:") are strings, so IntelliSense can't help. The last argument:

new {@class="caption"}

Is an anonymous object used to represent attributes. Because class is a reserved keyword in C#, you use the @ symbol to force C# to interpret "@class=" as a symbol (property name). To a front-end designer (someone familiar with HTML/CSS/JavaScript and other client technologies but not familiar with C# and Razor), most of the line is foreign. The entire line must be authored with no help from IntelliSense.+

Using the LabelTagHelper, the same markup can be written as:

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

With the Tag Helper version, as soon as you enter <l in the Visual Studio editor, IntelliSense displays matching elements:

[asp.net core] Tag Helpers 简介(转)

IntelliSense helps you write the entire line. The LabelTagHelper also defaults to setting the content of the asp-for attribute value ("FirstName") to "First Name"; It converts camel-cased properties to a sentence composed of the property name with a space where each new upper-case letter occurs. In the following markup:

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

generates:

 <label class="caption" for="FirstName">First Name</label>

The camel-cased to sentence-cased content is not used if you add content to the <label>. For example:

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

generates:

<label class="caption" for="FirstName">Name First</label>

The following code image shows the Form portion of the Views/Account/Register.cshtml Razor view generated from the legacy ASP.NET 4.5.x MVC template included with Visual Studio 2015.

[asp.net core] Tag Helpers 简介(转)

The Visual Studio editor displays C# code with a grey background. For example, the AntiForgeryToken HTML Helper:

@Html.AntiForgeryToken()

is displayed with a grey background. Most of the markup in the Register view is C#. Compare that to the equivalent approach using Tag Helpers:

[asp.net core] Tag Helpers 简介(转)

The markup is much cleaner and easier to read, edit, and maintain than the HTML Helpers approach. The C# code is reduced to the minimum that the server needs to know about. The Visual Studio editor displays markup targeted by a Tag Helper in a distinctive font.

Consider the Email group:

<div class="form-group">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>

Each of the "asp-" attributes has a value of "Email", but "Email" is not a string. In this context, "Email" is the C# model expression property for the RegisterViewModel.

The Visual Studio editor helps you write all of the markup in the Tag Helper approach of the register form, while Visual Studio provides no help for most of the code in the HTML Helpers approach. IntelliSense support for Tag Helpers goes into detail on working with Tag Helpers in the Visual Studio editor.

Tag Helpers compared to Web Server Controls

  • Tag Helpers don't own the element they're associated with; they simply participate in the rendering of the element and content. ASP.NET Web Server controls are declared and invoked on a page.
  • Web Server controls have a non-trivial lifecycle that can make developing and debugging difficult.
  • Web Server controls allow you to add functionality to the client Document Object Model (DOM) elements by using a client control. Tag Helpers have no DOM.
  • Web Server controls include automatic browser detection. Tag Helpers have no knowledge of the browser.
  • Multiple Tag Helpers can act on the same element (see Avoiding Tag Helper conflicts ) while you typically can't compose Web Server controls.
  • Tag Helpers can modify the tag and content of HTML elements that they're scoped to, but don't directly modify anything else on a page. Web Server controls have a less specific scope and can perform actions that affect other parts of your page; enabling unintended side effects.
  • Web Server controls use type converters to convert strings into objects. With Tag Helpers, you work natively in C#, so you don't need to do type conversion.
  • Web Server controls use System.ComponentModel to implement the run-time and design-time behavior of components and controls. System.ComponentModel includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components. Contrast that to Tag Helpers, which typically derive from TagHelper, and the TagHelper base class exposes only two methods, Process and ProcessAsync.

Customizing the Tag Helper element font

You can customize the font and colorization from Tools > Options > Environment > Fonts and Colors:

[asp.net core] Tag Helpers 简介(转)

[asp.net core] Tag Helpers 简介(转)的更多相关文章

  1. ASP&period;NET Core - Razor 页面简介

    简介 随着ASP.NET Core 2 即将来临,最热门的新事物是Razor页面.在之前的一篇文章中,我们简要介绍了ASP.NET Core Razor 页面. Razor页面是ASP.NET Cor ...

  2. ASP&period;NET Core 1&period;1 简介

    ASP.NET Core 1.1 于2016年11月16日发布.这个版本包括许多伟大的新功能以及许多错误修复和一般的增强.这个版本包含了多个新的中间件组件.针对Windows的WebListener服 ...

  3. ASP&period;NET Core &lpar;一&rpar;:简介

    下一篇:ASP.NET Core(二):入门 英文原版:Introduction to ASP.NET Core 关于ASP.NET Core ASP.NET Core 是一个全新的开源.跨平台框架, ...

  4. ASP&period;NET MVC应用迁移到ASP&period;NET Core及其异同简介

    ASP.NET Core是微软新推出支持跨平台.高性能.开源的开发框架,相比起原有的ASP.NET来说,ASP.NET Core更适合开发现代应用程序,如跨平台.Dorker的支持.集成现代前端开发框 ...

  5. ASP&period;NET Core之项目文件简介及配置文件与IOC的使用

    原文地址:https://www.cnblogs.com/knowledgesea/p/7079880.html 序言 在当前编程语言蓬勃发展与竞争的时期,对于我们.net从业者来说,.Net Cor ...

  6. ASP&period;NET Core MVC – Caching Tag Helpers

    简介 缓存可以大大提高应用程序加载时间和响应速度.我们可以使用缓存Tag Helpers缓存不会频繁更改的HTML内容. 在上一篇文章中,我们谈到了Tag Helpers,演示Tag Helpers能 ...

  7. ASP&period;NET Core MVC – Form Tag Helpers

    ASP.NET Core Tag Helpers系列目录 ASP.NET Core MVC Tag Helpers 介绍 ASP.NET Core MVC – Caching Tag Helpers ...

  8. ASP&period;NET Core MVC – Tag Helpers 介绍

    ASP.NET Core Tag Helpers系列目录,这是第一篇,共五篇: ASP.NET Core MVC – Tag Helpers 介绍 ASP.NET Core MVC – Caching ...

  9. ASP&period;NET Core 中文文档 第四章 MVC(3&period;6&period;1 )Tag Helpers 介绍

    原文:Introduction to Tag Helpers 作者:Rick Anderson 翻译:刘浩杨 校对:高嵩(Jack) 什么是 Tag Helpers? Tag Helpers 提供了什 ...

随机推荐

  1. 机器指令翻译成 JavaScript —— No&period;6 深度优化

    第一篇 中我们曾提到,JavaScript 最终还得经过浏览器来解析.因此可以把一些优化工作,交给脚本引擎来完成. 现代浏览器的优化能力确实很强,但是,运行时的优化终归是有限的.如果能在事先实现,则可 ...

  2. HDU 4857 逃生 (反向拓扑排序 &amp&semi; 容器实现)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4857 逃生 Time Limit: 2000/1000 MS (Java/Others)    Mem ...

  3. IIS发布文件出现:未能加载文件或程序集&OpenCurlyDoubleQuote;xxxx”或它的某一个依赖项。试图加载格式不正确的程序。

    解决方案:IIS——应用程序池—选中网站—高级设置——启用32位应用程序 :true.

  4. 使用Birt开发报表

    间隔一段时间未使用Birt开发报表后,本文章记录Birt开发报表的常遇到的开发问题及解决措施,方便自己和园内其他朋友学习. 一.Birt连接数据库配置 1.连接DB2数据库: 1.1.birt的数据连 ...

  5. html5 如何进行自定义属性的定义和查询

    <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>T ...

  6. 初级——程序如何打包成apk文件

    将Eclipse Android项目打包成APK文件是本文要介绍的内容,主要是来了解并学习Eclipse Android打包的内容,具体关于Eclipse Android内容的详解来看本文.Eclip ...

  7. Maven手动创建多模块项目

    Maven手动创建多模块项目 我要创建的项目名称是:unicorn,项目包含两个模块,分别是unicorn-core和unicorn-web.包的路径是com.goldpalm.tour. 项目创建流 ...

  8. leetcode -day19 Convert Sorted List to Binary Search Tree

    1.  Convert Sorted List to Binary Search Tree Given a singly linked list where elements are sorted ...

  9. 译《The Part-Time Parliament》——终于读懂了Paxos协议!

    最近的考古发现表明,在Paxos小岛上,尽管兼职议会成员都有逍遥癖,但议会模式仍然起作用.他们依旧保持了一致的会议记录,尽管他们频繁的进出会议室并且他们的信使还很健忘.Paxon议会协议提供了一种新方 ...

  10. MySQL中文排序

    按照汉字的拼音排序,用的比较多是在人名的排序中,按照姓氏的拼音字母,从A到Z排序: 如果存储姓名的字段采用的是GBK字符集,那就好办了,因为GBK内码编码时本身就采用了拼音排序的方法(常用一级汉字37 ...