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

时间:2015-05-20 11:33:06

标签: 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";
        }
    }
}

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

<demo asp-custom="hello world!">
    Please work this time :)
</demo>
我试了很多东西。删除了TargetElement属性或更改了命名空间。没有什么变化... 结果仍然相同。

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

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

这里的问题在哪里?

2 个答案:

答案 0 :(得分:6)

您可以通过向Views目录中的TagHelper文件添加addTagHelper指令,为自定义标记启用_ViewImports.cshtml处理:

@addTagHelper "*, YourMvcAssembly"

<强>更新

@yilmaz还需要添加对Microsoft.AspNet.Tooling.Razor的引用,详见下面的评论。

答案 1 :(得分:2)

这就是我目前对自定义标记帮助程序所具有的功能。我将其更改为目标演示元素。试试吧:

namespace TestingTagHelpers.TagHelpers
{
    using Microsoft.AspNet.Razor.Runtime.TagHelpers;
    using System;

    /// <summary>
    /// <see cref="ITagHelper"/> implementation targeting &lt;demo&gt; elements.
    /// </summary>
    //[TargetElement("demo")]
    public class DemoTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var childContent = context.GetChildContentAsync().Result;
            string demoContent = childContent.GetContent();
            string demo = context.AllAttributes["asp-custom"].ToString();

            output.TagName = "div";
            output.Attributes.Clear();
            output.Attributes["data-custom"] = demo;
            output.Content.SetContent(demoContent);
        }
    }
}