Hi,
I came looking on how to author a TagHelper that applies on the helper name itself.
For example asp-attribute-if-class="@condition".
Can you please include information about this in the documentation or link it?
⚠Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
I think I can help with this. @weitzhandler Can you provide a more specific example of what it is you’re looking to achieve?
@serpent5 thanks for your good intention!
I've already found the solution, but what I meant is how to author a tag-helper that reads anything after the tag, plus the assigned value.
For instance:
<input asp-class-if-active="@item.IsActive"/>
Will generate the element and add the active class if the condition is true, otherwise, that class won't be generated.
<input class="active"/>
Here's the code:
```c#
[HtmlTargetElement("", Attributes = ClassPrefix + "")]
public class IfAttributeClassTagHelper : TagHelper
{
private const string ClassPrefix = "asp-if-class-";
[HtmlAttributeName("class")]
public string CssClass { get; set; }
IDictionary<string, bool> _ClassValues;
[HtmlAttributeName("", DictionaryAttributePrefix = ClassPrefix)]
public IDictionary<string, bool> ClassValues
{
get
{
return _ClassValues ?? (_ClassValues =
new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase));
}
set { _ClassValues = value; }
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var items = ClassValues.Where(e => e.Value).Select(e => e.Key).ToList();
if (!string.IsNullOrEmpty(CssClass))
items.Insert(0, CssClass);
if (items.Any())
{
var classes = string.Join(" ", items);
output.Attributes.Add("class", classes);
}
}
}
```
Would be nice if the HtmlAttributeName and it's underlying functionality would have been documented.
Thanks a load again!
So true, all the built-in taghelpers have asp-XYZ attributes, but the doc doesn't explain how to create our own. This is quite an omission!
Thanks for contacting us. We believe that the question you've raised have been answered. If you still feel a need to continue the discussion, feel free to reopen it and add your comments.
Most helpful comment
@serpent5 thanks for your good intention!
I've already found the solution, but what I meant is how to author a tag-helper that reads anything after the tag, plus the assigned value.
For instance:
Will generate the element and add the
activeclass if the condition is true, otherwise, that class won't be generated.Here's the code:
```c#
[HtmlTargetElement("", Attributes = ClassPrefix + "")]
public class IfAttributeClassTagHelper : TagHelper
{
private const string ClassPrefix = "asp-if-class-";
```
Would be nice if the
HtmlAttributeNameand it's underlying functionality would have been documented.Thanks a load again!