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

时间:2015-09-29 14:15:10

标签: asp.net-mvc opengraph asp.net-core asp.net-core-mvc tag-helpers

我已经构建了二十二个HTML帮助程序,我正在转换为ASP.NET 5 MVC 6的标记助手,以生成Facebook Open Graph元标记。以下是“网站”类型的示例:

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对象类型都有一个特殊的命名空间,必须添加到头标记中,例如

_Layout.cshtml

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

我过去通过使用ViewBag和Namespace类上的OpenGraphWebsite getter属性设法使用HTML Helpers这样做:

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>

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

2 个答案:

答案 0 :(得分:1)

看起来在相应的GitHub issue中讨论/回答了这个问题。

答案 1 :(得分:0)

这是我在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
}