1

我在理解如何在HtmlTargetElement类属性的作品中显示分配给属性的字符串。我有几个问题,我认为会突出我的问题和理解。如何使用HtmlTargetElement(标签助手)中的属性属性来定位一个标签或另一个标签?

比方说,只有当以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

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

所以你的帮手如下mock版本:

[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(
[email protected]"<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> 
+0

感谢@DanielJG。我还了解到“查询选择”仅限于开始,结束,等于。在这里没有答案时,我发布了一个类似于css选择器的问题。 http://stackoverflow.com/questions/42879348/how-to-form-a-query-select-that-works-with-ands-and-ors?noredirect=1#comment72862592_42879348 –

+0

我找不到任何有关它的文档,但看[源](https://github.com/aspnet/Razor/blob/a7eb30ddca7872498696f2bb14c286105b0ae57c/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/HtmlTargetElementAttribute.cs#L52)它似乎仅限于那些用法 –

+0

[parser source](https://github.com/aspnet/Razor/blob/8f9ff1abd9b03838e967358de583fbae2c9fb693/src/Microsoft.CodeAnalysis.Razor/RequiredAttributeParser.cs)显示匹配属性值时只支持完全匹配,前缀和后缀。 –

相关问题