简体   繁体   English

在ASP.NET Core 2.1中添加自定义TagHelpers

[英]Add Custom TagHelpers in ASP.NET Core 2.1

I've followed the ASP.NET Core documentation to the letter and spent a significant amount of time trawling stack overflow trying to implement a simple custom TagHelper with no success. 我严格按照ASP.NET Core文档进行操作,并花费了大量时间来拖曳堆栈溢出,以尝试实现简单的自定义TagHelper并没有成功。

Would anyone be able to advise on any gotcha's or known bugs? 任何人都可以就任何陷阱或已知错误提出建议吗?

Application Properties: 应用程序属性:

AssemblyName: AmpWeb
Target Framework .NET Core 2.1

NuGet Packages NuGet软件包

Microsoft.AspNetCore.All 2.1.2

Enviroment 环境

OS: Windows 7 (x64)
SDK: Microsoft .NET Core SDK 2.1.302 (x64)
IDE: Visual Studio 2017 Professional 15.7.4

TagHelpers/EmailTagHelper.cs TagHelpers / EmailTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AmpWeb.TagHelpers
{
    [HtmlTargetElement(Attributes = "email")]
    public class EmailTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "a";    // Replaces <email> with <a> tag
        }
    }
}

Views/_ViewImports.cshtml 查看/ _ViewImports.cshtml

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

Index.cshtml Index.cshtml

<h1>Hello World</h1>
<email>WHY</email>

Output 产量

<h1>Hello World</h1>
<email>WHY</email>

It's a subtle issue but an important one. 这是一个微妙的问题,但重要的。 The issue is this line of code [HtmlTargetElement(Attributes = "email")] 问题是这行代码[HtmlTargetElement(Attributes = "email")]

If you remove it it should work by using your <email>WHY</email> markup. 如果将其删除,则可以使用<email>WHY</email>标记来工作。 You could also replace it with [HtmlTargetElement("email")] but it's not actually even needed in this case because the framework can infer that info from the name of the class EmailTagHelper . 您也可以将其替换为[HtmlTargetElement("email")]但实际上在这种情况下甚至不需要它,因为框架可以从类EmailTagHelper的名称推断该信息。

By including [HtmlTargetElement(Attributes = "email")] you are saying that you want the tag helper invoked via an attribute on any tag. 通过包含[HtmlTargetElement(Attributes = "email")]您表示您希望通过任何标签上的属性调用标签助手。 So invoking it would be something like <div email></div> or <span email></span> for example. 因此,调用它将类似于<div email></div><span email></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM