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

前端 未结 2 755
天命终不由人
天命终不由人 2021-01-12 09:07

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

2条回答
  •  醉酒成梦
    2021-01-12 09:26

    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 _classValues;
    
        [HtmlAttributeName("", DictionaryAttributePrefix = ClassPrefix)]
        public IDictionary ClassValues
        {
            get {
                return _classValues ?? (_classValues = 
                    new Dictionary(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:

    result for Active = true and Display = true is:

提交回复
热议问题