【问题标题】:How to use Attributes Property in HtmlTargetElement (Tag Helpers) to target one tag or another?如何使用 HtmlTargetElement(标签助手)中的 Attributes 属性来定位一个或另一个标签?
【发布时间】:2017-03-18 01:31:53
【问题描述】:

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

假设我们只想在 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>

【问题讨论】:

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


    【解决方案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)并匹配 make 属性的前缀条件 ^gm 的出现。

    生成的 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>
    

    【讨论】:

    • 谢谢@DanielJG。我还收集到“QuerySelected Like”仅限于 startwith、endwith、equalto。当这里没有答案时,我用 css 选择器发布了一个类似的问题。 stackoverflow.com/questions/42879348/…
    • 我找不到任何合适的文档,但是查看the source 似乎仅限于这些用法
    • parser source表示匹配属性值时只支持全匹配、前缀和后缀。
    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 2020-02-08
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多