How to use Attributes Property in HtmlTargetElement (Tag Helpers) to target one tag or another?

痴心易碎 提交于 2020-01-25 00:23:26

问题


I'm wrestling with understanding how to show the string assigned to Attributes in the HtmlTargetElement class attribute works. I have a couple questions that I think will highlight my issue and understanding.

Let's say we want activate an Html Element only when make starts with gm and there is any model. I think there is a way to do this with a single class attribute (not multiple ones).

I'm trying the following but it is just a SWAG and does not work. I'd appreciate tips so I can understand what the doc means when it says that this attribute can take a "query selector like string".

The Tag Helper Class

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

and the razor markup

<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:


It actually works like you were expecting. The only bit your are missing is that Attributes is a comma-separated list of attributes so when specifying more than one you need the commas as in Attributes = "[make^=gm],[model]".

So the following mock version of your helper:

[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>");
    }
}

With the following razor markup:

<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>

Will match only the first and third appearances as they are the only ones with both required attributes (make and model) and matching the prefix condition ^gm for the make attribute.

The resulting html looks like this:

<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>


来源:https://stackoverflow.com/questions/42869464/how-to-use-attributes-property-in-htmltargetelement-tag-helpers-to-target-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!