Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-tag-helpers

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


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>

Solution

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