ASP.NET Core 中的標籤協助程式Tag Helpers in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

什麼是標籤協助程式What are Tag Helpers

標記協助程式可讓伺服器端程式碼參與建立和轉譯檔案中的 HTML 元素 Razor 。Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. 例如,內建 ImageTagHelper 可以將版本號碼附加至映像名稱。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). 有許多適用於一般工作 (例如建立表單和連結、載入資產等) 的內建標籤協助程式,還有更多位於公用 GitHub 存放庫及作為 NuGet 套件來提供。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. 標籤協助程式是以 C# 編寫,並根據項目名稱、屬性名稱或上層標籤來設定目標 HTML 項目。Tag Helpers are authored in C#, and they target HTML elements based on element name, attribute name, or parent tag. 例如,套用 LabelTagHelper 屬性時,內建 LabelTagHelper 可以將目標設為 HTML <label> 項目。For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied. 如果您熟悉htmlhelper,標記協助程式會減少在瀏覽器中的 Html 和 c # 之間的明確轉換 Razor 。If you're familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views. 在許多情況下,HTML 協助程式都會提供特定標籤協助程式的替代方式,但請務必辨識標籤協助程式未取代 HTML 協助程式,而且每個 HTML 協助程式都沒有標籤協助程式。In many cases, HTML Helpers provide an alternative approach to a specific Tag Helper, but it's important to recognize that Tag Helpers don't replace HTML Helpers and there's not a Tag Helper for each HTML Helper. 標籤協助程式與 HTML 協助程式的比較會詳述差異。Tag Helpers compared to HTML Helpers explains the differences in more detail.

標籤協助程式所提供的內容What Tag Helpers provide

HTML 易懂的開發體驗大部分的情況下,使用標籤協助程式的 Razor 標記看起來就像標準 HTML。An HTML-friendly development experience For the most part, Razor markup using Tag Helpers looks like standard HTML. 使用 HTML/CSS/JavaScript 熟悉的前端設計工具可以在 Razor 不學習 c # 語法的情況下進行編輯 Razor 。Front-end designers conversant with HTML/CSS/JavaScript can edit Razor without learning C# Razor syntax.

用來建立 HTML 和 Razor 標記的豐富 IntelliSense 環境,這與 HTML helper 相比,是先前在 views 中建立標記的方法 Razor 。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. 標籤協助程式與 HTML 協助程式的比較會詳述差異。Tag Helpers compared to HTML Helpers explains the differences in more detail. 標籤協助程式的 IntelliSense 支援說明 IntelliSense 環境。IntelliSense support for Tag Helpers explains the IntelliSense environment. 即使是熟悉 c # 語法的開發人員,使用標籤協助程式 Razor 比撰寫 c # 標記更具生產力 Razor 。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. 在過去,編輯映像之後,必須變更名稱,而且需要更新 Web 應用程式中映像的每個參考。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. 這不僅非常耗費人力, (您可能會遺漏參考、不小心輸入錯誤的字串等等。 ) 內建的 ImageTagHelper 可以自動為您執行這項工作。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. ImageTagHelper 可以將版本號碼附加到映像名稱後面;因此,只要映像變更,伺服器就會自動產生映像的新唯一版本。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. 使用 ImageTagHelper,此健全性和人力節省基本上是免費的。This robustness and labor savings comes essentially free by using the ImageTagHelper.

大部分的內建的標籤協助程式都可以在標準的 HTML 元素中使用,可為元素提供伺服器端的屬性。Most built-in Tag Helpers target standard HTML elements and provide server-side attributes for the element. 例如,在 [檢視/帳戶]** 資料夾內許多檢視中所使用的 <input> 元素會包含 asp-for 屬性。For example, the <input> element used in many views in the Views/Account folder contains the asp-for attribute. 此屬性會擷取指定之模型屬性的名稱,並將其放入轉譯的 HTML 中。This attribute extracts the name of the specified model property into the rendered HTML. 請考慮 Razor 使用下列模型的觀點:Consider a Razor view with the following model:

public class Movie
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }

下列 Razor 標記:The following Razor markup:

<label asp-for="Movie.Title"></label>

產生下列 HTML:Generates the following HTML:

<label for="Movie_Title">Title</label>

asp-for 屬性由 LabelTagHelper 中的 For 提供。The asp-for attribute is made available by the For property in the LabelTagHelper. 如需詳細資訊,請參閱編寫標籤協助程式See Author Tag Helpers for more information.

管理標籤協助程式範圍Managing Tag Helper scope

標籤協助程式範圍是透過 @addTagHelper@removeTagHelper 和 "!" 退出字元的組合所控制。Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the "!" opt-out character.

@addTagHelper 讓標籤協助程式可用@addTagHelper makes Tag Helpers available

如果您建立名為 AuthoringTagHelpers 的新 ASP.NET Core Web 應用程式,則會將下列 Views/_ViewImports.cshtml 檔案新增至您的專案:If you create a new ASP.NET Core web app named AuthoringTagHelpers, the following Views/_ViewImports.cshtml file will be added to your project:

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

@addTagHelper 指示詞讓標籤協助程式可供檢視使用。The @addTagHelper directive makes Tag Helpers available to the view. 在此情況下,視圖檔案是pages/_ViewImports. cshtml,預設會由pages資料夾和子資料夾中的所有檔案繼承;讓標籤協助程式可供使用。In this case, the view file is Pages/_ViewImports.cshtml, which by default is inherited by all files in the Pages folder and subfolders; making Tag Helpers available. 上述程式碼使用萬用字元語法 ( " * " ) ,指定在Views目錄或子目錄中的每個視圖檔案中,指定元件 (TagHelpers) 中的所有標籤協助程式都可供使用。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 subdirectory. @addTagHelper 後面的第一個參數指定要載入的標籤協助程式 (使用 "*" 表示所有標籤協助程式),而第二個參數 "Microsoft.AspNetCore.Mvc.TagHelpers" 指定包含標籤協助程式的組件。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 是內建 ASP.NET Core 標籤協助程式的組件。Microsoft.AspNetCore.Mvc.TagHelpers is the assembly for the built-in ASP.NET Core Tag Helpers.

若要公開此專案中的所有標籤協助程式 (這會建立名為 AuthoringTagHelpers 的組件),請使用下列內容: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

如果您的專案包含具有預設命名空間 (AuthoringTagHelpers.TagHelpers.EmailTagHelper) 的 EmailTagHelper,則您可以提供標籤協助程式的完整名稱 (FQN):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

若要使用 FQN 將標籤協助程式新增至檢視,請依序新增 FQN (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. 萬用字元語法可讓您在 FQN 中插入萬用字元 "*" 作為尾碼。The wildcard syntax allows you to insert the wildcard character "*" as the suffix in an FQN. 例如,下列任何指示詞都會顯示 EmailTagHelperFor example, any of the following directives will bring in the EmailTagHelper:

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

如先前所述,將指示詞新增 @addTagHelperviews/_ViewImports. cshtml檔案,讓views目錄和子目錄中的所有視圖檔案都能使用標記協助程式。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 subdirectories. 如果您想要選擇只向那些檢視公開標籤協助程式,則可以使用特定檢視檔案中的 @addTagHelper 指示詞。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 會移除標籤協助程式@removeTagHelper removes Tag Helpers

@removeTagHelper 有兩個參數與 @addTagHelper 相同,而且會移除先前新增的標籤協助程式。The @removeTagHelper has the same two parameters as @addTagHelper, and it removes a Tag Helper that was previously added. 例如,套用至特定檢視的 @removeTagHelper 會從檢視中移除指定的標籤協助程式。For example, @removeTagHelper applied to a specific view removes the specified Tag Helper from the view. Views/Folder/_ViewImports.cshtml 檔案中使用 @removeTagHelper,會從 Folder 的所有檢視中移除所指定的標籤協助程式。Using @removeTagHelper in a Views/Folder/_ViewImports.cshtml file removes the specified Tag Helper from all of the views in Folder.

使用 _ViewImports.cshtml 檔案控制標籤協助程式範圍Controlling Tag Helper scope with the _ViewImports.cshtml file

您可以將 _ViewImports.cshtml 新增至任何檢視資料夾,而且檢視引擎會套用該檔案和 Views/_ViewImports.cshtml 檔案中的指示詞。You can add a _ViewImports.cshtml to any view folder, and the view engine applies the directives from both that file and the Views/_ViewImports.cshtml file. 如果您已為 Home 檢視新增空白 Views/Home/_ViewImports.cshtml 檔案,則不會進行變更;因為 _ViewImports.cshtml 檔案是加總的。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. 您新增至 Views/Home/_ViewImports.cshtml 檔案的任何 @addTagHelper 指示詞 (不在預設 Views/_ViewImports.cshtml 檔案中),只會向 Home 資料夾中的檢視公開這些標籤協助程式。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 ("!"). 例如,在包含標籤協助程式退出字元的 <span> 中,停用 Email 驗證: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. (將退出字元新增至開頭標籤時,Visual Studio 編輯器會將退出字元自動新增至結尾標籤)。(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.

使用 @tagHelperPrefix 以明確使用標籤協助程式Using @tagHelperPrefix to make Tag Helper usage explicit

@tagHelperPrefix 指示詞可讓您指定標籤前置詞字串以啟用標籤協助程式支援,並明確使用。The @tagHelperPrefix directive allows you to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit. 例如,您可以將下列標記新增至 Views/_ViewImports.cshtml 檔案:For example, you could add the following markup to the Views/_ViewImports.cshtml file:

@tagHelperPrefix th:

在下列程式碼影像中,標籤協助程式前置詞設定為 th:,因此只有使用前置詞 th: 的項目才支援標籤協助程式 (啟用標籤協助程式的項目具有特殊字型)。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). <label><input> 項目具有標籤協助程式前置詞並且已啟用標籤協助程式,而 <span> 項目則否。The <label> and <input> elements have the Tag Helper prefix and are Tag Helper-enabled, while the <span> element doesn't.


套用至 @addTagHelper 的相同階層規則也會套用至 @tagHelperPrefixThe same hierarchy rules that apply to @addTagHelper also apply to @tagHelperPrefix.

自行結尾的標籤協助程式Self-closing Tag Helpers

許多標籤協助程式無法作為自行結尾的標籤。Many Tag Helpers can't be used as self-closing tags. 某些標籤協助程式專門用作自行結尾的標籤。Some Tag Helpers are designed to be self-closing tags. 使用非專門用作自行結尾的標籤協助程式會隱藏轉譯輸出。Using a Tag Helper that was not designed to be self-closing suppresses the rendered output. 讓標籤協助程式自行結尾,會在轉譯輸出中產生自行結尾的標籤。Self-closing a Tag Helper results in a self-closing tag in the rendered output. 如需詳細資訊,請參閱編寫標籤協助程式中的這項附註For more information, see this note in Authoring Tag Helpers.

標記協助程式屬性/宣告中的 c #C# in Tag Helpers attribute/declaration

標記協助程式不允許在專案的屬性或標記宣告區域中採用 c #。Tag Helpers do not allow C# in the element's attribute or tag declaration area. 例如,下列程式碼無效:For example, the following code is not valid:

<input asp-for="LastName"  
       @(Model?.LicenseId == null ? "disabled" : string.Empty) />

上述程式碼可以撰寫為:The preceding code can be written as:

<input asp-for="LastName" 
       disabled="@(Model?.LicenseId == null)" />

標籤協助程式的 IntelliSense 支援IntelliSense support for Tag Helpers

當您在 Visual Studio 中建立新的 ASP.NET Core web 應用程式時,它會新增 NuGet 套件 Razor AspNetCore。工具」。When you create a new ASP.NET Core web app in Visual Studio, it adds the NuGet package "Microsoft.AspNetCore.Razor.Tools". 這是新增標籤協助程式工具的套件。This is the package that adds Tag Helper tooling.

請考慮撰寫 HTML <label> 項目。Consider writing an HTML <label> element. 只要您在 Visual Studio 編輯器中輸入 <l,IntelliSense 就會顯示相符的項目:As soon as you enter <l in the Visual Studio editor, IntelliSense displays matching elements:


您不只可以取得 HTML 協助,還可以取得圖示 (其下的 "@" symbol with "<>")。Not only do you get HTML help, but the icon (the "@" symbol with "<>" under it).


識別標籤協助程式設為目標的項目。identifies the element as targeted by Tag Helpers. 純 HTML 項目 (例如 fieldset) 會顯示 "<>" 圖示。Pure HTML elements (such as the fieldset) display the "<>" icon.

純 HTML <label> 標籤會以棕色字型顯示 HTML 標籤 (具有預設 Visual Studio 色彩佈景主題)、以紅色顯示屬性,並以藍色顯示屬性值。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.


在您輸入 <label 之後,IntelliSense 會列出可用的 HTML/CSS 屬性以及設為目標的標籤協助程式屬性:After you enter <label, IntelliSense lists the available HTML/CSS attributes and the Tag Helper-targeted attributes:


IntelliSense 陳述式完成可讓您輸入 Tab 鍵,來完成具有所選取值的陳述式:IntelliSense statement completion allows you to enter the tab key to complete the statement with the selected value:


只要輸入標籤協助程式屬性,標籤和屬性字型就會變更。As soon as a Tag Helper attribute is entered, the tag and attribute fonts change. 使用預設 Visual Studio "Blue" 或 "Light" 色彩佈景主題,而且字型為粗體紫色。Using the default Visual Studio "Blue" or "Light" color theme, the font is bold purple. 如果要使用 "Dark" 佈景主題,則字型是粗體藍綠色。If you're using the "Dark" theme the font is bold teal. 本文件中的影像是使用預設佈景主題所取得。The images in this document were taken using the default theme.


您可以在雙引號 ("") 內輸入 Visual Studio CompleteWord 快速鍵 (Ctrl+空格鍵是預設值,而且現在可以使用 C#,就像使用 C# 類別一樣。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 會顯示頁面模型上的所有方法和屬性。IntelliSense displays all the methods and properties on the page model. 因為屬性類型是 ModelExpression,所以可以使用方法和屬性。The methods and properties are available because the property type is ModelExpression. 在下列影像中,我正在編輯 Register 檢視,因此 RegisterViewModel 可供使用。In the image below, I'm editing the Register view, so the RegisterViewModel is available.


IntelliSense 會列出頁面上模型可用的屬性和方法。IntelliSense lists the properties and methods available to the model on the page. 豐富的 IntelliSense 環境可協助您選取 CSS 類別:The rich IntelliSense environment helps you select the CSS class:



標籤協助程式與 HTML 協助程式的比較Tag Helpers compared to HTML Helpers

標籤協助程式會附加至 views 中的 HTML 專案 Razor ,而HTML協助程式則是當做在視圖中與 html 一起使用的方法叫用 Razor 。Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as methods interspersed with HTML in Razor views. 請考慮下列 Razor 標記,這會建立具有 CSS 類別 "caption" 的 HTML 標籤:Consider the following Razor markup, which creates an HTML label with the CSS class "caption":

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

At (@) 符號會告訴 Razor 這是程式碼的開頭。The at (@) symbol tells Razor this is the start of code. 下兩個參數 ("FirstName" 和 "First Name:") 是字串,因此 IntelliSense 沒有幫助。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. 由於 class 是 C# 中的保留關鍵字,因此您可以使用 @ 符號來強制 C# 將 @class= 解譯為符號 (屬性名稱)。Because class is a reserved keyword in C#, you use the @ symbol to force C# to interpret @class= as a symbol (property name). 在前端設計工具 (熟悉 HTML/CSS/JavaScript 和其他用戶端技術,但不熟悉 c # 和) 的使用者 Razor ,大部分的那一行都是外部的。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. 您必須編寫整行,而 IntelliSense 沒有任何幫助。The entire line must be authored with no help from IntelliSense.

使用 LabelTagHelper,可以將相同的標記撰寫為:Using the LabelTagHelper, the same markup can be written as:

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

使用標籤協助程式版本時,只要您在 Visual Studio 編輯器中輸入 <l,IntelliSense 就會顯示相符的項目:With the Tag Helper version, as soon as you enter <l in the Visual Studio editor, IntelliSense displays matching elements:


IntelliSense 可協助您撰寫整行。IntelliSense helps you write the entire line.

下列程式碼影像顯示從 Visual Studio 隨附的 ASP.NET 4.5. x MVC 範本產生的Views/Account/Register. cshtml視圖的表單部分。 RazorThe following code image shows the Form portion of the Views/Account/Register.cshtml Razor view generated from the ASP.NET 4.5.x MVC template included with Visual Studio.


Visual Studio 編輯器會以灰色背景顯示 C# 程式碼。The Visual Studio editor displays C# code with a grey background. 例如,AntiForgeryToken HTML 協助程式:For example, the AntiForgeryToken HTML Helper:


以灰色背景顯示。is displayed with a grey background. 註冊檢視中的大部分標記都是 C#。Most of the markup in the Register view is C#. 將該方法與使用標籤協助程式的對等方法進行比較:Compare that to the equivalent approach using Tag Helpers:


與 HTML 協助程式方法相較之下,標記更為簡潔,而且更容易讀取、編輯和維護。The markup is much cleaner and easier to read, edit, and maintain than the HTML Helpers approach. C# 程式碼會減少到伺服器所知道的最小值。The C# code is reduced to the minimum that the server needs to know about. Visual Studio 編輯器會以特殊字型顯示標籤 (tag) 協助程式設為目標的標籤 (markup)。The Visual Studio editor displays markup targeted by a Tag Helper in a distinctive font.

請考慮使用 Email 群組: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>

每個 "asp-" 屬性的值都是 "Email",但 "Email" 不是字串。Each of the "asp-" attributes has a value of "Email", but "Email" isn't a string. 在此內容中,"Email" 是 RegisterViewModel 的 C# 模型運算式屬性。In this context, "Email" is the C# model expression property for the RegisterViewModel.

Visual Studio 編輯器可協助您撰寫註冊表單之標籤 (tag) 協助程式方法中的所有標籤 (markup),而 Visual Studio 不提供 HTML 協助程式方法中大部分程式碼的協助。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 支援會詳述如何在 Visual Studio 編輯器中使用標籤協助程式。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 伺服器控制項是在頁面上宣告和叫用。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.

  • 網頁伺服器控制項可讓您使用用戶端控制項,來新增用戶端文件物件模型 (DOM) 項目的功能。Web Server controls allow you to add functionality to the client Document Object Model (DOM) elements by using a client control. 標籤協助程式沒有 DOM。Tag Helpers have no DOM.

  • Web 伺服器控制項包括自動瀏覽器偵測。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.

  • 標籤協助程式可以修改設為其範圍之 HTML 項目的標籤和內容,但不會直接修改頁面上的其他任何項目。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. 使用標籤協助程式時,您可以使用 C# 以原生方式工作,因此不需要進行類型轉換。With Tag Helpers, you work natively in C#, so you don't need to do type conversion.

  • 網頁伺服器控制項使用 System.ComponentModel,來實作元件和控制項的執行階段和設計階段行為。Web Server controls use System.ComponentModel to implement the run-time and design-time behavior of components and controls. System.ComponentModel 包含基底類別和介面,以便實作屬性和類型轉換器、繫結至資料來源,以及授權元件。System.ComponentModel includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components. 與一般衍生自 TagHelper 的標籤協助程式相反,而且 TagHelper 基底類別只會公開兩個方法:ProcessProcessAsyncContrast 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

您可以從 [工具] [選項] [環境] [字型 > Options > Environment > 和色彩] 自訂字型和顏色標示You can customize the font and colorization from Tools > Options > Environment > Fonts and Colors:


內建的 ASP.NET Core 標記協助程式Built-in ASP.NET Core Tag Helpers

錨點標記協助程式Anchor Tag Helper

快取標記說明程式Cache Tag Helper

元件標記說明程式Component Tag Helper

分散式快取標籤說明程式Distributed Cache Tag Helper

環境標記協助程式Environment Tag Helper

表單標記協助程式Form Tag Helper

表單動作標記協助程式Form Action Tag Helper

影像標記協助程式Image Tag Helper

輸入標籤說明程式Input Tag Helper

分頁說明程式Label Tag Helper

連結分頁説明程式Link Tag Helper

部分標記說明程式Partial Tag Helper

文稿標記說明程式Script Tag Helper

選擇標記說明程式Select Tag Helper

文字區域標記說明程式Textarea Tag Helper

驗證訊息標記說明程式Validation Message Tag Helper

驗證摘要標記說明程式Validation Summary Tag Helper

其他資源Additional resources