asp.net core tag helper for conditionally add class to an element

心已入冬 提交于 2019-12-01 04:30:42

Ability to add a conditional css class by following tagHelper provides. this code like AnchorTagHelper asp-route-* for add route values acts.

[HtmlTargetElement("div", Attributes = ClassPrefix + "*")]
public class ConditionClassTagHelper : TagHelper
{
    private const string ClassPrefix = "condition-class-";

    [HtmlAttributeName("class")]
    public string CssClass { get; set; }

    private 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.ToArray());
            output.Attributes.Add("class", classes);
        }
    }
}

in _ViewImports.cshtml add reference to taghelper as following

@addTagHelper "*, WebApplication3"

Use tagHelper in View:

<div condition-class-active="Model.Active" condition-class-show="Model.Display">
</div>

result for Active = true and Display = true is:

<div class="active show">
</div>

There's no default way to do what you're asking. You would have to write a TagHelper that did that logic for you. Aka

[HtmlTargetElement(Attributes = "asp-active")]
public class FooTagHelper : TagHelper
{
    [HtmlAttributeName("asp-active")]
    public bool Active { get; set; }

    public override void Process(TagHelperOutput output, TagHelperContext context)
    {
        if (Active)
        {
            // Merge your active class attribute onto "output"'s attributes.
        }
    }
}

And then the HTML would look like:

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