ASP.NET Core應用程式8:標籤助手

一纸年华發表於2024-05-29

1 準備工作

  繼續使用上一章專案程式碼,修改Startup.cs。

 public void ConfigureServices(IServiceCollection services) {
     services.AddDbContext<DataContext>(opts => {
         opts.UseSqlServer(Configuration[
             "ConnectionStrings:ProductConnection"]);
         opts.EnableSensitiveDataLogging(true);
     });
     services.AddControllersWithViews().AddRazorRuntimeCompilation();
     services.AddRazorPages().AddRazorRuntimeCompilation();
     services.AddSingleton<CitiesData>();
 }
 public void Configure(IApplicationBuilder app, DataContext context) {
     app.UseDeveloperExceptionPage();
     app.UseStaticFiles();
     app.UseRouting();
     app.UseEndpoints(endpoints => {
         endpoints.MapControllers();
         endpoints.MapDefaultControllerRoute();
         endpoints.MapRazorPages();
     });
     SeedData.SeedDatabase(context);
 }

  修改Views/Home/index.cshtml。

@model Product
@{  
    Layout = "_SimpleLayout";
}

<table class="table table-striped table-bordered table-sm">
    <thead>
        <tr>
            <th colspan="2">Product Summary</th>
        </tr>
    </thead>
    <tbody>
        <tr><th>Name</th><td>@Model.Name</td></tr>
        <tr>
            <th>Price</th>
            <td>@Model.Price.ToString("c")</td>
        </tr>
        <tr><th>Category ID</th><td>@Model.CategoryId</td></tr>
    </tbody>
</table>

  在Views/Shard資料夾下新增_SimpLayout.cshtml。

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="/lib/twitter-bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="m-2">
        @RenderBody()
    </div>
</body>
</html>

  請求http://localhost:5000/home。

2 建立標籤助手

  下面介紹建立和應用標籤助手的過程,為tr元素設定引導css類如下。

<tr tr-color="primary">
    <th colspan="2">Product Summary</th>
</tr>

  轉化為這樣。

<tr class="bg-primary text-white text-center">
    <th colspan="2">Product Summary</th>
</tr>

2.1 定義標籤助手類

  建立TagHelpers資料夾,新增TrTagHelper.cs檔案。

public class TrTagHelper : TagHelper
{
    public string BgColor { get; set; } = "dark";
    public string TextColor { get; set; } = "white";
    
    public override void Process(TagHelperContext context,
            TagHelperOutput output)
    {
        output.Attributes.SetAttribute("class",
            $"bg-{BgColor} text-center text-{TextColor}");
    }
}

  標籤助手是從 TagHelper 類派生的,該類在 Microsoft.AspNetCore.Razor.TagHelpers 名稱空間中定義。TagHelper 類定義了一個 Process 方法,它被子類覆蓋以實現轉換元素的行為。
  標籤助手的名稱組合了它轉換的元素的名稱,後跟 TagHelper。在本例中,類名 TrTagHelper表示這是一個操作tr 元素的標籤助手。

(1)接收上下文資料

  標籤助手透過 TagHelperContext 類的例項接收關於它們正在轉換的元素的資訊,這個例項為 Process 方法的引數接收,如下定義了描述的屬性。

  • AllAttributes:此屬性返回一個特性的只讀字典,其中包含應用於被轉換元素的特性,按名稱和索引排序。
  • Items:此屬性返回一個字典,該字典用於在標籤助手之間進行協調。
  • Uniqueld:此屬性返回被轉換元素的唯一識別符號。

(2)生成輸出

  Process 方法透過配置作為引數接收的 TagHelperOutput 物件來轉換元素。TagHelperOutput象首先描述出現在檢視中的 HTML, 元素,然後透過以下描述的屬性和方法進行修改。

  • TagName:此屬性用於獲取或設定輸出元素的標記名。
  • Attributes:此屬性返回一個包含輸出元素屬性的字典。
  • Content:此屬性返回一個 TagHelperContent物件,該物件用於設定元素的內容。
  • GetChildContentAsync():這個非同步方法提供了對將要轉換的元素內容的訪問。
  • PreElement:該屬性返回一個 TagHelperContext物件,該物件用於在輸出元素之前在檢視中插入內容。
  • PostElement:該屬性返回一個 TagHelperContext 物件,該物件用於在輸出元素之後在檢視中插入內容。
  • PreContent:此屬性返回一個 TagHelperContext 物件,用於在輸出元素的內容之前插入內容。
  • PostContent:此屬性返回一個 TagHelperContext物件,用於在輸出元素的內容之後插入內容。
  • TagMode:此屬性指定如何使用 TagMode 列舉的值寫入輸出元素。
  • SupressOuput():呼叫該方法會從檢視中排除一個元素。

  在 TrTagHelper 類中,使用 Attributes 字典向指定引導樣式的 HTML 元素新增了一個 class 屬性,包括 BgColor 和 TextColor 屬性的值。其效果是,可透過將 bg-color 和 text-color 屬性設定為引導名稱(如 primary、info 和 danger)來指定 tr 元素的背景顏色。

2.2 註冊標籤助手

  在使用標籤助手類之前,它們必須在@addTagHelper 指令中註冊。標籤助手可以應用到的組檢視或頁面取決於使用@addTagHelper 指令的位置。
  對於單個檢視或頁面,指令出現在CSHTML檔案中。要使標籤助手更廣泛地可用,可以將其新增到檢視匯入檔案中。
  希望本章建立的標籤助手在應用程式的任何地方都可用,這意味著@addTagHelper 指令新增到 Views 和 Pages 資料夾的 _ViewImports.cshtml 檔案中。在前一章中用於應用檢視元件的 vc 元素是一個標籤助手,這就是啟用標籤助手所需的指令位於 _ViewImports.cshtm 檔案的原因。

@addTagHelper *,MyWebApp

  引數的第一部分指定標籤助手類的名稱,並支援萬用字元,第二部分指定定義它們的程式集的名稱。@addTagHelper 指令使用萬用字元選擇 MyWebApp 程式集中的所有名稱空間,其效果是在專案中任何地方定義的標籤助手都可在任何控制器檢視中使用。Razor Pages 資料夾的Viewlmports.cshtm 檔案中有一個相同的語句。

2.3 使用標籤助手

  使用標籤助手轉換元素,將屬性新增到tr元素,它將應用標籤助手。Home 資料夾的 Index.cshtml 檔案中使用標籤助手。瀏覽器請求 http://ocalhost:5000/home。

<tr bg-color="info" text-color="white">
    <th colspan="2">Product Summary</th>
</tr>

  應用屬性的tr元素進行了轉換,但這不是顯示的唯一更改。預設情況下,標籤助手應用於特定型別的所有元素,這意味著檢視中的所有tr元素都使用標籤助手類中定義的預設值進行轉換,因為沒有定義任何特性。

2.4 縮小標籤助手的範圍

  可使用 HTMLTargetElement 元素控制由標籤助手轉換的元素範圍,TrTagHelper.cs 檔案中縮小範圍。

[HtmlTargetElement("tr", Attributes = "bg-color,text-color", ParentTag = "thead")]
public class TrTagHelper : TagHelper

  HTMLTargetElement 屬性描述了應用標籤助手的元素。第一個引數指定元素型別,並支援表以下描述的其他命名屬性。

  • Attributes:指定標籤助手應僅用於具有一組給定屬性(以逗號分隔)的元素。以星號編結尾的屬性名稱將被視為字首,這樣 bg-*將匹配 bg-color、bg-size 等。
  • ParentTag:指定標籤助手應僅應用於給定型別元素中包含的元素。
  • TagStructure:指定標籤助手僅應用於其標記結構對應於TagStructure 列舉中給定值的元素,該列舉定義了Unspecified、NormalOrSelfClosing 和 WithoutEndTag。

  Amibutes 屬性支援 CSS 屬性選擇器語法,這樣[bg-color]匹配具有 bg-color 屬性的元素,[bg-color primary]匹配 bg-color 屬性值為 primary 的元素,[bg-color^=p]配 bg-color 屬性值以p開頭的元素。
  程式碼中應用於標籤助手的屬性匹配如下tr 元素,包含 bg-color 和 text-color 屬性,父元素是 thead。
  瀏覽器請求http://localhost:5000/home/index/1,標籤助手的範圍縮小了。

2.5 擴充套件標籤助手的範圍

  HTMLTargetElement 屬性還可用於擴大標籤助手的範圍,以便匹配更大範圍的元素。這是透過將屬性的第一個引數設定為星號(字元)來實現的,匹配任何元素。

[HtmlTargetElement("*", Attributes = "bg-color,text-color")]

  使用星號時必須小心,因為很容易匹配過大範圍,並選擇不應該轉換的元素。更安全的中間方法是為每類元素應用 HTMLTargetElement 屬性。

[HtmlTargetElement("tr", Attributes = "bg-color,text-color")]
[HtmlTargetElement("td", Attributes = "bg-color")]

  修改Home 資料夾的 Index.cshtml 檔案中新增屬性。並使用瀏覽器請求 http:/localhost:5000/home/index/1。

<td bg-color="dark">@Model.Price.ToString("c")</td>

3 高階標籤助手功能

3.1 建立快捷元素

  標籤助手並不僅限於轉換標準 HTML 元素,還可用常用內容替換定製元素。這是一個有用的特性,可使檢視更簡潔,意圖更明顯。為演示這一點,Index.cshtml 用定製的 HTML 元素替換了 thead 元素。

<tablehead bg-color="dark">Product Summary</tablehead>

  將一個名為TableHeadTagHelper.cs 的類新增到TagHelpers 資料夾。

[HtmlTargetElement("tablehead")]
public class TableHeadTagHelper : TagHelper
{
    public string BgColor { get; set; } = "light";
    public override async Task ProcessAsync(TagHelperContext context,
            TagHelperOutput output)
    {
        output.TagName = "thead";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.SetAttribute("class",
            $"bg-{BgColor} text-white text-center");
        string content = (await output.GetChildContentAsync()).GetContent();

        output.Content.SetHtmlContent($"<tr><th colspan=\"2\">{content}</th></tr>");
    }
}

  這個標籤助手是非同步的,並且覆蓋了ProcessAsync方法,這樣它就可以訪問它轉換的元素的現有內容。ProcessAsync方法使用TagHelperOuput物件的屬性來生成一個完全不同的元素:TagName屬性用於指定thead元素,TagMode屬性用於指定使用開始和結束標記編寫元素。Attibutes.SetAttribute方法用於定義類屬性,Content屬性用於設定元素內容。
  元素的現有內容是透過非同步GetchidContentAsync方法獲得的,該方法返回TagHelperconent物件。這與TaeHeperOuput.Content屬性返回的物件相同,並允許使用相同型別,通如下描述的方法來檢査和更改元素的內容。

  • GetContent():此方法以字串形式返回 HTML 元素的內容。
  • SetContent(text):此方法設定輸出元素的內容。對字串引數進行編碼,以便安全地包含在Html素中。
  • SetHtmlContent(html):此方法設定輸出元素的內容。假設字串引數是安全編碼的。應當謹慎使用。
  • Append(text):此方法安全地編碼指定的字串,並將其新增到輸出元素的內容中。
  • AppendHtml(html):此方法將指定的字串新增到輸出元素的內容中,而不執行任何編碼。應當謹慎使用。
  • Clear():此方法刪除輸出元素的內容。

  元素的現有內容透過 GetContent 元素讀取,然後使用 SetHtmlconm方法設定它。效果是在 tr和 th 元素中對已轉換元素中的現有內容換行。重啟 並導航到 http://localhost:5000/home/index/1, 就會看到標籤助手的效果。

<tablehead bg-color="dark">Product Summary</tablehead>

  以上程式碼將被轉換為:

<thead class="bg-dark text-white text-center">
  <tr>
     <th colspan="2">Product Summary</th>
  </tr>
</thead>

  注意,轉換後的元素不包括 bg-color 屬性。與標籤助手定義的屬性匹配的屬性將從輸出元素中刪除;如有必要,則必須顯式地重新定義它們。

3.2 以程式設計方式建立元素

  在生成新的 HTML 元素時,可以使用標準的 C#字串格式來建立所需的內容,這就是在 TableHeadTagHelper.cs 中採用字串的方法。這樣做有效但需要密切注意以避免拼寫錯誤。
  更健壯的方法是使用 TagBuilder類,它是在 Microsot.AspNetCore.Mvc.Rendering 名稱空間中定義的,並允許以更結構化的方式建立元素。 TaglelperContent 方法接收 TagBuilde 物件,這將便於在標籤助手中建立 HTML 內容,修改TableHeadTagHelper.cs中ProcessAsync方法,如下所示。

......
string content = (await output.GetChildContentAsync()).GetContent();
//output.Content.SetHtmlContent($"<tr><th colspan=\"2\">{content}</th></tr>");

TagBuilder header = new TagBuilder("th");
header.Attributes["colspan"] = "2";
header.InnerHtml.Append(content);

TagBuilder row = new TagBuilder("tr");
row.InnerHtml.AppendHtml(header);
output.Content.SetHtmlContent(row);

3.3 追加、附加內容和元素

  TagHelperOutput 類提供了四個屬性,可以很容易地將新內容注入檢視中,以便包用元素或元素內容。

  • PreElement:此屬性用於在目標元素之前向檢視中插入元素
  • PostElement:此屬性用於在目標元素之後向檢視中插入元素
  • PreContent:此屬性用於在任何現有內容之前將內容插入目標元素
  • PostContent:此屬性用於在任何現有內容之後將內容插入目標元素

  接下來解釋如何在目標元素周圍和內部插入內容。

(1)在輸出元素周圍插入內容

  前兩個 TagHelperOuput 屬性是 PreElement 和 PostElement,它們用於在輸出元素之前和之向檢視插入元素。為演示這些屬性的用法,將一個名為 WrapperTagHelper.cs 的類檔案新增到 TagHelpers 資料夾中。

[HtmlTargetElement("*", Attributes = "[wrap=true]")]
public class ContentWrapperTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        TagBuilder elem = new TagBuilder("div");
        elem.Attributes["class"] = "bg-primary text-white p-2 m-2";
        elem.InnerHtml.AppendHtml("wrapper");
        output.PreElement.AppendHtml(elem);
        output.PostElement.AppendHtml(elem);
    }
}

  這個標籤助手轉換 wrap屬性值為 true 的元素,使用 preElement 和 PostElement 屬性在蠊元素之前和之後新增 div元素。將一個元素新增到由標籤助手轉換的索引檢視中。
  在Home/Index.cshtml檢視中新增如下。

<div class="m-2" wrap="true">Inner Content</div>

  使用瀏覽器請求 http://localhost:5000/home/index/1。 響應包括轉換後的元素將是這樣。

<div class="bg-primary text_white p-2 m-2">wrapper</div>
<div class="m-2" wrap="true">Inner Content</div>
<div class="bg-primary text-white p-2 m-2">wrapper</div>

(2)在輸出元素中插入內容

  PreContent 和 PostContent屬性用於在輸出元素中圍繞原始內容插入內容。為演示這個特性將一個名為 HighlightTagHelper.cs 的類檔案新增到 TagHelpers 資料夾中。

 [HtmlTargetElement("*", Attributes = "[highlight=true]")]
 public class HighlightTagHelper : TagHelper
 {
     public override void Process(TagHelperContext context, TagHelperOutput output)
     {
         output.PreContent.SetHtmlContent("<b><i>");
         output.PostContent.SetHtmlContent("</i></b>");
     }
 }

  這個標籤助手在輸出元素的內容周圍插入b和i元素。如下程式碼將wrap屬性新增到Inde檢視中的一個表格單元格中。

<tr><th>Name</th><td highlight="true">@Model.Name</td></tr>

  使用瀏覽器請求 http://localhost:5000/home/index/1。 響應包括轉換後的元素將是這樣。

<td highlight="true"><b><i>Kayak</i></b></td>

3.4 獲取檢視上下文資料

  標籤助手的一個常見用途是轉換元素,使它們包含當前請求或檢視模型/頁面模型的詳細資訊,這需要訪問上下文資料。要建立這種型別的標籤助手,將一個名為 RouteDataTagHelper.cs 的檔案新增到 TagHelpers 資料夾。

[HtmlTargetElement("div", Attributes = "[route-data=true]")]
public class RouteDataragHelper : TagHelper
{
    [ViewContext]
    [HtmlAttributeNotBound]
    public ViewContext Context { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.Attributes.SetAttribute("class", "bg-primary m-2 p-2");
        TagBuilder list = new TagBuilder("ul");
        list.Attributes["class"] = "list-group";
        RouteValueDictionary rd = Context.RouteData.Values;
        if (rd.Count > 0)
        {
            foreach (var kvp in rd)
            {
                TagBuilder item = new TagBuilder("li");
                item.Attributes["class"] = "list-group-item";
                item.InnerHtml.Append($"{kvp.Key}:{kvp.Value}");
                list.InnerHtml.AppendHtml(item);
            }
            output.Content.AppendHtml(list);
        }
        else
        {
            output.Content.Append("No route data");
        }
    }
}

  標籤助手轉換具有 route-data 屬性(其值為 true)的 div 元素,並使用路由系統獲得的段變數列表填充輸出元素。
  為獲取路由資料,新增了一個名為 Context 的屬性,並用兩個特性裝飾它。
  ViewContext 屬性的值應該在建立標籤助手類的新例項時分配一個 ViewConte物件,它提供了正在呈現的檢視的詳細資訊,包括路由資料。
  如果在 div 元素上定義了匹配的屬性,HTMLAttributeNotBound 屬性將阻止為該屬性分配值。

  向主控制器的 Index.cshtml 檢視新增了一個元素,這個元素由新的標籤助手進行轉換。使用瀏覽器請求 http://localhost:5000/home/index/1。 響應將包括路由系統匹配的段變數的列表。

<div route-data="true"></div>

3.5 使用模型表示式

  標籤助手可以操作檢視模型,裁剪它們執行的轉換或它們建立的輸出。要了解這個特性是何工作的,將一個名為 ModelRowTagHielpercs 的類檔案新增到 TagHelpers 資料夾中。

[HtmlTargetElement("tr", Attributes = "for")]
public class ModelRowTagHelper : TagHelper
{
    public string Format { get; set; }
    public ModelExpression For { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagMode = TagMode.StartTagAndEndTag;
        TagBuilder th = new TagBuilder("th");
        th.InnerHtml.Append(For.Name);
        output.Content.AppendHtml(th);
        TagBuilder td = new TagBuilder("td");
        if (Format != null && For.Metadata.ModelType == typeof(decimal))
        {
            td.InnerHtml.Append(((decimal)For.Model).ToString(Format));
        }
        else
        {
            td.InnerHtml.Append(For.Model.ToString());
        }
        output.Content.AppendHtml(td);
    }
}

  這個標籤助手轉換具有 for 特性的 tr 元素。這個標籤助手的重要部分是 For屬性的ModelExpression型別,該屬性用於接收 for 特性的值。
  希望對檢視模型的一部分進行操作時,將使用 ModelExpression 類,最簡單的解釋方法是向前跳轉並顯示如何在檢視中應用標籤助手。修改Home/Index.cshtml。

<tbody>
    <tr for="Name" />
    <tr for="Price" format="c" />
    <tr for="CategoryId" />
</tbody>

  for 特性的值是檢視模型類定義的屬性的名稱。在建立標籤助手時,檢測 For 屬性的型別,並分配一個描述所選屬性的 ModelExpression 物件。
  對於示例標籤助手,使用了三個值得描述的基本功能。第一個是獲得模型屬性的名稱(For.Name),這樣就可以把它包含在輸出元素中。第二個功能是獲取模型屬性的型別(For.Metadata.ModelType),這樣可以決定是否格式化值。第三個功能是獲取屬性的值(For.Model),以便將其包含在響應中。

3.6 標籤助手之間的協調

  TagHelperContext.Items 屬性提供一個字典,用於操作元素及其後代的標籤助手。為了演示Items 集合的使用,將一個名為 CoordinatingTagHelpers.cs 的類檔案新增到 TagHelpers 資料夾中。

[HtmlTargetElement("tr", Attributes = "theme")]
public class RowTagHelper : TagHelper
{
    public string Theme { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        context.Items["theme"] = Theme;
    }
}

[HtmlTargetElement("th")]
[HtmlTargetElement("td")]
public class CellTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (context.Items.ContainsKey("theme"))
        {
            output.Attributes
                .SetAttribute("class", $"bg-{context.Items["theme"]} text-white");
        }
    }
}

  第一個標籤助手對具有 theme 屬性的 tr 元素進行操作。協調標籤助手可轉換它們自己的元素但本示例只是將 theme 屬性的值新增到 Itens 字典中,以便對操作t 元素中包含的元素的標籤助手可用。第二個標籤助手對 t 和 td 元素進行操作,並使用 Items 字典中的 theme 值為其輸出元素設定引導樣式。
  向主控制器的 Index 檢視新增了應用協調標籤助手的元素。

<tr theme="primary">
    <th>Name</th>
    <td>@Model.Name</td>
</tr>
<tr theme="secondary">
    <th>Price</th>
    <td>@Model.Price.ToString("c")</td>
</tr>
<tr theme="info">
    <th>Category</th>
    <td>@Model.CategoryId</td>
</tr>

  使用測覽器請求 himp://localhost:5000/home。theme 元素的值已經從一個標籤助手傳遞到另一個標籤助手,並且應用顏色主題時不需要每個被轉換的元素上定義屬性。

3.7 抑制輸出元素

  透過呼叫作為 Process 方法引數接收的 TagHelperOutput物件上的 SuppressOutput 方法,可使用標籤助手來防止元素包含在 HTM 響應中。
  向主控制器的 Imdex 檢視加了一個元素,只有在檢視模型的 Price 屬性超過指定值時才應該顯示該元素。

<div show-when-gt="500" for="Price">
    <h5 class="bg-danger text-white text-center p-2">
        Warning: Expensive Item
    </h5>
</div>

  show-when-gt屬性指定了 div 元素應在其上顯示的值,而 for 屬性選擇要檢査的模型屬性。要建立管理元素(包括響應)的標籤助手,將一個名為SelectiveTagHelper.cs 的類檔案新增到TagHelpers 資料夾。

[HtmlTargetElement("div", Attributes = "show-when-gt, for")]
public class SelectiveTagHelper : TagHelper
{
    public decimal ShowWhenGt { get; set; }
    public ModelExpression For { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (For.Model.GetType() == typeof(decimal)
            && (decimal)For.Model <= ShowWhenGt)
        {
            output.SuppressOutput();
        }
    }
}

  除非超過閾值,否則標籤助手使用模型表示式訪問屬性並呼叫SuppressOutput 方法。要檢視效果,使用瀏覽器請求 http://localhost:5000/home/index/1http://localhost:5000/home/index/5。 第一個 URL 選擇的產品的 Price 屬性值小於閾值,因此該元素被抑制。第二個 URI, 選擇的產品的 Price 屬性值超過了閾值,因此顯示該元素。

4 使用標籤助手元件

  標籤助手元件提供了將標籤助手用作服務的另一種方法。當需要設定標籤助手來支援另一個服務或中介軟體元件時可能非常有用。

4.1 建立標籤助手元件

  標籤助手元件是從 TagHelperComponent 類派生的,該類提供了與TagHelper基類類似的Api。
  在 TagHelpers 資料夾下新增 TimeTagHelperComponent.cs 檔案。

public class TimeTagHelperComponent : TagHelperComponent
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        string timestamp = DateTime.Now.ToLongTimeString();
        if (output.TagName == "body")
        {
            TagBuilder elem = new TagBuilder("div");
            elem.Attributes.Add("class", "bg-info text-white m-2 p-2");
            elem.InnerHtml.Append($"Time: {timestamp}");
            output.PreContent.AppendHtml(elem);
        }
    }
}

  標籤助手元件不指定它們轉換的元素,併為已經配置標籤助手元件特性的每個元素呼叫Process方法。預設情況下,應用標籤助手元件來轉換 head 和 body 元素。這意味著標籤助手類必須檢査輸出元素的 TagName 屬性,以確保它們只執行預期的轉換。
  以上標籤助手元件查詢 body 元素,並使用 PreContent 屬性在元素的其餘內容之前插入包含時間戳的 div 元素。
  在Startup.cs中註冊標籤助手元件。

services.AddTransient<ITagHelperComponent, TimeTagHelperComponent>();

  AddTransient 方法用於確保使用標籤助手元件類的例項來處理每個請求。要檢視標籤助手元件的效果,使用瀏覽器請求 http://localhost:5000/home。 該響應以及來自應用程式的其他所有HTML響應包含由標籤助手元件生成的內容。

4.2 展開標籤助手的元素選擇

  預設情況下,標籤助手元件只處理 head 和 body 元素,但可透過建立一個派生自TagHelperComponentTagHelper 的類來選擇其他元素。
  TagHelpers 資料夾下新增 TableFooterTagHelperComponemt.cs 類。

[HtmlTargetElement("table")]
public class TableFooterSelector : TagHelperComponentTagHelper
{
    public TableFooterSelector(ITagHelperComponentManager mgr, ILoggerFactory log)
        : base(mgr, log) { }
}

public class TableFooterTagHelperComponent : TagHelperComponent
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (output.TagName == "table")
        {
            TagBuilder cell = new TagBuilder("td");
            cell.Attributes.Add("colspan", "2");
            cell.Attributes.Add("class", "bg-dark text-white text-center");
            cell.InnerHtml.Append("Table Footer");
            TagBuilder row = new TagBuilder("tr");
            row.InnerHtml.AppendHtml(cell);
            TagBuilder footer = new TagBuilder("tfoot");
            footer.InnerHtml.AppendHtml(row);
            output.PostContent.AppendHtml(footer);
        }
    }
}

  TableFooterSelector 類派生自TagHelperComponentTagHelper,並使用 HTMLTargetElement 屬性裝飾它,該屬性擴充套件了由應用程式的標籤助手元件處理的元素範圍。在本例中,屬性選擇 table 元素。
  在同一個檔案中定義的 TableFooterTagHelperComponent 類是一個標籤助手元件,它透過新增tfoot 元素來轉換表元素,tfoot 元素表示表的頁尾。
  標籤助手元件必須註冊為服務來接收轉換的元素。

services.AddTransient<ITagHelperComponent, TableFooterTagHelperComponent>();

  使用瀏覽器請求呈現表的 URL,如 http://localhost:5000/home。 每個表將包含一個表的頁尾。

相關文章