Search code examples
asp.net-coretag-helpers

ASP.NET Core tag helper for conditionally adding a class to an element


In Asp.Net MVC we can add class conditionally as following code:

<div class="choice @(Model.Active?"active":"")">
</div>

How can do this by using tagHelper and by remove else part in condition.


Solution

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