如何为剃刀创建自定义标签助手?

Yve*_*ves 7 c# asp.net asp.net-mvc asp.net-core-mvc tag-helpers

我正在尝试在MVC 6中创建自定义标记帮助程序,但无法使其工作.

这是我在Web应用程序项目中定义的演示标记助手类.

namespace Microsoft.AspNet.Mvc.TagHelpers
{
    [TargetElement("demo", Attributes = CustomAttributeName)]
    public class DemoTagHelper : TagHelper
    {
        private const string CustomAttributeName = "asp-custom";

        [HtmlAttributeName(CustomAttributeName)]
        public string Custom { get; set; }

        public string Value { get; set; }


        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.Attributes["foo"] = "bar";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在我的观点中使用它的方式:

<demo asp-custom="hello world!">
    Please work this time :)
</demo>
Run Code Online (Sandbox Code Playgroud)

我尝试了很多东西.删除了TargetElement属性或更改了命名空间.没有什么变化......结果仍然相同.

顺便说一句,我的Microsoft.AspNet.Mvc.TagHelpers版本是6.0.0-beta4.

也许我必须在某个地方注册我的标签助手?我查看了MVC源代码,他们没有在任何地方引用自己的标记助手.所以我认为不需要注册.

这里的问题在哪里?

hut*_*oid 6

您可以TagHelper通过向Views目录中找到addTagHelper_ViewImports.cshtml文件添加指令来启用自定义标记的处理:

@addTagHelper "*, YourMvcAssembly"
Run Code Online (Sandbox Code Playgroud)

更新

@yilmaz还需要Microsoft.AspNet.Tooling.Razor在评论中添加如下所述的引用.