如何使用HtmlTargetElement(Tag Helpers)中的Attributes属性来定位一个或多个标签?

时间:2017-03-18 01:31:54

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

我正在努力了解如何在HtmlTargetElement类属性中显示分配给Attributes的字符串。我有几个问题,我认为这些问题将突出我的问题和理解。

假设我们只想在make以gm开头且有任何模型时激活一个Html元素。我认为有一种方法可以使用单个类属性(不是多个属性)来完成此操作。

我正在尝试以下内容,但它只是一个SWAG并且不起作用。我很感激提示,所以当我说这个属性可以采用“像字符串一样的查询选择器”时,我可以理解文档的含义。

标记助手类

[HtmlTargetElement("auto-price", Attributes = "[make^=gm][model]")]
public class AutoPriceTagHelper : TagHelper
{

和剃刀标记

<auto-price make="gm" model="volt" ></auto-price>
<auto-price make="ford" model="mustang"></auto-price>
<auto-price make="ford" ></auto-price>
<auto-price test></auto-price>

1 个答案:

答案 0 :(得分:1)

它实际上就像你期待的那样。您遗失的唯一一点是Attributes 是以逗号分隔的属性列表所以当指定多个时,您需要使用Attributes = "[make^=gm],[model]"中的逗号。

所以你的助手的以下模拟版本:

[HtmlTargetElement("auto-price", Attributes = "[make^=gm],[model]")]
public class AutoPriceTagHelper : TagHelper
{
    public string Make { get; set; }
    public string Model { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "ul";
        output.Content.SetHtmlContent(
$@"<li>Make: {Make}</li>
<li>Model: {Model}</li>");
    }
}

使用以下剃须刀标记:

<auto-price make="gm" model="volt" ></auto-price>
<auto-price make="ford" model="mustang"></auto-price>
<auto-price make="gmfoo" model="the foo"></auto-price>
<auto-price make="gmbar"></auto-price>
<auto-price test></auto-price>

仅匹配第一次和第三次出现,因为它们是唯一具有所需属性(makemodel)并且匹配^gm的前缀条件make的出现} attribute。

生成的html如下所示:

<ul><li>Make: gm</li>
<li>Model: volt</li></ul>
<auto-price make="ford" model="mustang"></auto-price>
<ul><li>Make: gmfoo</li>
<li>Model: the foo</li></ul>
<auto-price make="gmbar"></auto-price>
<auto-price test=""></auto-price>