【问题标题】:How to create custom tag helpers for razor?如何为剃须刀创建自定义标签助手?
【发布时间】:2015-08-01 15:05:18
【问题描述】:

我正在尝试在 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 源代码,他们没有在任何地方引用自己的标签助手。所以我认为不需要注册。

问题出在哪里?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-core-mvc tag-helpers


【解决方案1】:

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

@addTagHelper "*, YourMvcAssembly"

更新

@yilmaz 还需要添加对Microsoft.AspNet.Tooling.Razor 的引用,如下面的 cmets 中所述。

【讨论】:

  • 现在我设法让它工作了。我需要添加两件事,这是其中之一。另一个是对 Microsoft.AspNet.Tooling.Razor 程序集的引用。因此,也许您也可以将其添加到您的答案中,以使其更加完整以供将来使用。
  • @Yilmaz 不错,我也将其添加到答案中。谢谢。 :)
【解决方案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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2018-05-19
    • 2019-06-05
    • 2013-02-14
    • 2012-05-24
    • 2016-01-17
    • 2019-08-01
    相关资源
    最近更新 更多