Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 542
Mohammad Akbari Avatar asked Feb 20 '17 05:02

Mohammad Akbari


People also ask

What is the difference between HTML helper and tag helpers?

HtmlHelpers vs. Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.

What is tag helper in ASP.NET Core and its type?

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This feature is available in ASP.NET Core 2.0 or later. ASP.NET Core includes two built-in Tag Helper Components: head and body . They're located in the Microsoft.

What attribute name do you use on your tag helper C# class to determine whether a tag helper will execute on a given HTML element?

Using HtmlTargetElement attribute, we can provide a tag helper target. It passes an attribute parameter that specifies the HTML element which contains an HTML attribute named, for example, "my-first-tag-helper". It will match and process the override method in the class it will run.

What is helper class in ASP.NET Core?

HtmlHelper is a class which is introduced in MVC 2. It is used to create HTML controls programmatically. It provides built-in methods to generate controls on the view page. In this topic we have tabled constructors, properties and methods of this class.


1 Answers

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>
like image 152
Mohammad Akbari Avatar answered Oct 26 '22 14:10

Mohammad Akbari