2017-03-18 232 views
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)顯示匹配屬性值時只支持完全匹配,前綴和後綴。 –