1

我正在努力理解如何在 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>
4

1 回答 1

2

它实际上像您期望的那样工作。您缺少的唯一一点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

生成的 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>
于 2017-03-19T10:57:48.240 回答