Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional attributes in tag helpers

I have a tag helper along the lines of the following:

[HtmlTargetElement("foo", Attributes = "bar")]
public class FooTagHelper : TagHelper

[HtmlAttributeName("bar")]
public bool Bar { get; set; }

When I add the following to a view, the tag helper processes the target as expected:

<foo bar="true"></foo>

However, what I would like to do is make bar optional e.g. <foo></foo> If it has been left off, I would like it to default to false

Is this possible? This source code comment for the HtmlTargetElementAttribute.Attributes property seems to indicate not:

// Summary:
A comma-separated System.String of attribute names the HTML element must contain
for the Microsoft.AspNet.Razor.TagHelpers.ITagHelper to run. * at the end of an attribute name acts as a prefix match.

like image 514
Mister Epic Avatar asked Sep 11 '25 09:09

Mister Epic


1 Answers

You could remove "bar" from being a required attribute.

You can do that by overriding the Process method and checking whether the attribute exists. If it does not, add the Bar attribute using its name and value. You could explicitly set the value to false but the property Bar is false by default anyway.

[HtmlTargetElement("foo")]
public class FooTagHelper : TagHelper
{
    [HtmlAttributeName("bar")]
    public bool Bar { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (!output.Attributes.ContainsName(nameof(Bar)))
        {
            output.Attributes.Add(nameof(Bar), Bar);
        }
    }
}

Cheers!

If you have not yet done so, I would suggest taking a look at the documentation available here https://docs.asp.net/projects/mvc/en/latest/views/tag-helpers/index.html.

like image 175
Mat Hellums Avatar answered Sep 13 '25 23:09

Mat Hellums