ASP.NET 5 MVC 6 中的命名标签助手

Named Tag Helpers in ASP.NET 5 MVC 6

我已经构建了两个 HTML 助手,我正在转换为 ASP.NET 5 MVC 6 的标签助手,以生成 Facebook Open Graph 元标签。这是 'website' 类型的示例:

Index.cshtml

<open-graph-website title="Page Title" 
                    main-image="new OpenGraphImage(
                        "~/img/open-graph-1200x630.png", 
                        "image/png", 
                        1200, 
                        630)"
                  determiner="Blank"
                  site-name="Site Title">

每个 Open Graph 对象类型都有一个特殊的命名空间,必须将其添加到 head 标记中,例如

_Layout.cshtml

<html>
<head prefix="website: http://ogp.me/ns/website#">
</head>
<body>
    <!-- ...Omitted -->
</body>
</html>

我过去使用 HTML Helpers 通过使用 ViewBag 和 OpenGraphWebsite OpenGraphWebsite 属性 上的 Namespace getter 属性 设法做到了这一点49=] 像这样:

Index.cshtml

ViewBag.OpenGraph = new OpenGraphWebsite(
    "Page Title",
    new OpenGraphImage("/img/open-graph-1200x630.png", "image/png", 1200, 630)
    {
        Determiner = OpenGraphDeterminer.Blank,
        SiteName = "Site Title"
    };

_Layout.cshtml

<html>
<head @(ViewBag.OpenGraph == null ? null : ViewBag.OpenGraph.Namespace)>
    @Html.OpenGraph((OpenGraphMetadata)ViewBag.OpenGraph);
</head>
<body>
    <!-- ...Omitted -->
</body>
</html>

有没有办法用标签助手实现类似的结果?命名标签助手或引用它的某种方式?

看起来这是 discussed/answered 在对应的 GitHub issue.

这是我在 GitHub 上提出的问题的答案。请注意,此标记助手会自动运行,因为它仅针对 head 元素。

[TargetElement("open-graph-website", Attributes = nameof(Title) + "," + nameof(MainImage), TagStructure = TagStructure.WithoutEndTag)]
public class OpenGraphWebsiteTagHelper : OpenGraphMetadataTagHelper // Inherits from TagHelper
{
    // ... Omitted
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        context.Items[typeof(OpenGraphMetadata)] = this.GetNamespaces();
        output.Content.SetContent(this.ToString());
    }
}

[TargetElement("head")]
public class OpenGraphNamespacePrefixTagHelper : TagHelper
{
     private const string PrefixAttributeName = "prefix";

    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        context.Items.Add(typeof(OpenGraphMetadata), null);

        await context.GetChildContentAsync();

        string namespaces = context.Items[typeof(OpenGraphMetadata)] as string;
        if (namespaces != null)
        {
            output.Attributes.Add(PrefixAttributeName, namespaces);
        }
    }
}

我仍将尝试添加所需的虚拟对象 属性。这将迫使用户选择使用标签助手,而不是仅仅因为他们添加了标签助手 DLL 就自动 运行。如果可以将无值属性添加到标签助手以促进 bool 属性的此功能,那就太好了:

<head asp-open-graph-prefix>
Rather than:
<head asp-open-graph-prefix="true">

[TargetElement("head", Attributes = OpenGraphPrefixAttributeName)]
public class OpenGraphNamespacePrefixTagHelper : TagHelper
{
    private const string OpenGraphPrefixAttributeName = "asp-open-graph-prefix";

    [HtmlAttributeName(OpenGraphPrefixAttributeName)]
    public bool DUMMY { get; set; }

    // ..Omitted
}