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

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

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

2条回答
  •  没有蜡笔的小新
    2021-01-12 09:15

    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:

提交回复
热议问题