在 ASP.NET Core 有一項叫 Tag Helpers 的功能,它可以用來簡化在 View 上的 html code,例如官方提供的範例中,簡化過的 email tag:

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

    public string MailTo { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";    // Replaces <email> with <a> tag

        var address = MailTo + "@" + EmailDomain;
        output.Attributes.SetAttribute("href", "mailto:" + address);
        output.Content.SetContent(address);
    }
}

這樣在 View 上可簡化成:<email mail-to="aaa3">aaa3</email>

而以下範例則是單純生出一個連到 Google 的 html a tag:

[HtmlTargetElement("test")]
public class TestTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";
        output.Attributes.SetAttribute("href", "https://www.google.com.tw");
        output.Content.SetContent("Test Content");
    }
} 

在 View 上就只要寫 <test></test>,而寫出這些類別後,如要使用則必需在 _ViewImports.cshtml 加入 @addTagHelper *, <Assembly Name> 這一行,才能在 View 上使用自己寫的 Tag Helpers

參考資料