Add CSS Class to html element in a TagHelper

asp.net core custom tag helper
tag helpers vs html helpers
asp.net core tag helpers not working
tag helpers mvc 5
asp-for tag helper

In an ASP.NET Core View I have the following:

<div class="message" message=""></div>

And I the a Tag Helper with the following TagHelper:

[HtmlTargetElement("div", Attributes = MessageName)]
public class MessageTagHelper : TagHelper {

  private const String MessageName = "message";

  [HtmlAttributeName(MessageName)]
  public String Message { get; set; }

  [HtmlAttributeNotBound, ViewContext]
  public ViewContext ViewContext { get; set; }


  public override void Process(TagHelperContext context, TagHelperOutput output) {

    String message;
    Boolean defined = ViewContext.HttpContext.Request.Cookies.TryGetValue("_message", out message);

    if (defined) {
      ViewContext.HttpContext.Response.Cookies.Delete("_message");
      output.Attributes.Add("class", "active");
      output.Content.Append(message);
    }
  }
}

On the following code line I need to add "active" as CSS Class.

output.Attributes.Add("class", "active");

However, this does nothing. Message remains only with class "message".

What am I missing?

As of ASP.NET Core 2.1 you can use the TagHelperOutputExtensions class provided by Microsoft to add your "active" CSS class in one line of code.

using Microsoft.AspNetCore.Mvc.TagHelpers;
using System.Text.Encodings.Web;
...
public override void Process(TagHelperContext context, TagHelperOutput output)
{
    ...
    output.AddClass("active", HtmlEncoder.Default);
    ...
}

ASP Net Core TagHelper Add CSS Class, What is the HTML output of the above code, can you post snippet of that? The tag helper in the OP works, but instead of appending a sup element to all you need to do is to add a css class to the label element itself and use CSS to style the  Using the tag helper, we can extend our existing HTML elements or create our own custom HTML elements. The custom tag helper is nothing but the class that implements the ITagHelper interface. However, .NET Core MVC provides us the implementation of this interface. To create custom tag helper, the first step is to create a class that inherits

@Shyju's answer is mostly correct, but there's a lot of extraneous code that's unnecessary. The following is enough to handle it in ASP.NET Core 2.0:

var classes = output.Attributes.FirstOrDefault(a => a.Name == "class")?.Value;
output.Attributes.SetAttribute("class", $"active {classes}");

ASP Net Core TagHelper Add CSS Class - html, The tag helper in the OP works, but instead of appending a sup element to contain the asterisk, I think all you need to do is to add a css class to the label element  In the snippet above, we created a CSS class called “newClass“. This class does three things: It sets the color of the element’s text to red. It sets the font weight to bold. And it sets the font style to italic. As you can see, it’s pretty simple stuff! The HTML element. Now, let’s create an example HTML element:

I think you should remove the existing TagHelperAttribute for css class from the Attributes collection and add a new one which has all the classes (Existing and your new "active" class)

The below code should work.

var existingClass = output.Attributes.FirstOrDefault(f => f.Name == "class");
var cssClass = string.Empty;
if (existingClass != null)
{
    cssClass = existingClass.Value.ToString();       
}
cssClass = cssClass + " active";
var ta = new TagHelperAttribute("class", cssClass);
output.Attributes.Remove(existingClass);
output.Attributes.Add(ta);

Tag Helpers in ASP.NET Core, Tag Helpers are authored in C#, and they target HTML elements based on element name, To add a Tag Helper to a view using an FQN, you first add the FQN Razor markup, which creates an HTML label with the CSS class "caption":​. A tag helper is any class that implements the ITagHelper interface. However, when you author a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method. Create a new ASP.NET Core project called AuthoringTagHelpers. You won't need authentication for this project.

The other answers here does not check current css class to avoid duplicate values. Here, I wrote an extension to add a css class with proper checks to ensure clean html at output:

public static class GeneralExtionsions
{
    //the white space chars valid as separators between every two css class names
    static readonly char[] spaceChars = new char[] { ' ', '\t', '\r', '\n', '\f' };

    /// <summary> Adds or updates the specified css class to list of classes of this TagHelperOutput.</summary>
    public static void AddCssClass(this TagHelperOutput output, string newClass)
    {
        //get current class value:
        string curClass = output.Attributes["class"]?.Value?.ToString(); //output.Attributes.FirstOrDefault(a => a.Name == "class")?.Value?.ToString();

        //check if newClass is null or equal to current class, nothing to do
        if (string.IsNullOrWhiteSpace(newClass) || string.Equals(curClass, newClass, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        //append newClass to end of curClass if curClass is not null and does not already contain newClass:
        if (!string.IsNullOrWhiteSpace(curClass) 
            && curClass.Split(spaceChars, StringSplitOptions.RemoveEmptyEntries).Contains(newClass, StringComparer.OrdinalIgnoreCase)
            )
        {
            newClass = $"{curClass} {newClass}";
        }

        //set new css class value:
        output.Attributes.SetAttribute("class", newClass);

    }

}

Tag Helper Components in ASP.NET Core, The tag helper will generate a div enclosing an unordered list, with each list item having a link to a page of data. The resulting HTML should look like this: The CSS classes that have been applied are from the BootStrap styles, so the Add("​itemscope itemtype", "http://schema.org/Organization");; output. I don't know how to get elements of my HTML ("div" for example) and add additional CSS attributes to it. All these are about doing a feature as Vue could easily do. In Vue code, we could certainly add any attribute to a component and pass them down to the first element in the component.

Creating Custom Tag Helpers in Razor Pages, Common uses for tag helpers include URLs for forms using the application's Tag helpers can be used to apply certain CSS classes to HTML. The tag helper will recognize the bs-button-color attribute and use its value to  Stack Overflow Public using VB.NET and I'm trying to apply a css class to a Html.ActionLink How can I add a class attribute to an HTML element generated by

Understanding Tag Helpers in ASP.NET Core MVC – Programming , Next the Process function added the CSS class 'btn btn-{property value}' which becomes For example if I add the custom HTML element like: Fullscreen Video Modal Boxes Delete Modal Timeline Scroll Indicator Progress Bars Skill Bar Range Sliders Tooltips Display Element Hover Popups Collapsible Calendar HTML Includes To Do List Loaders Star Rating User Rating Overlay Effect Contact Chips Cards Flip Card Profile Card Product Card Alerts Callout Notes Labels Circles Style HR Coupon List Group List Without Bullets Responsive Text Cutout Text Glowing Text Fixed Footer Sticky Element Equal Height Clearfix Responsive Floats Snackbar

Custom Tag Helper in ASP.NET Core, The tag helper enables us to run server-side code to generate HTML, CSS, The custom tag helper is nothing but the class that implements the In this example, I have registered “*”, so it will add all the tag helpers within the  Note: Do not add a space between the property value and the unit (such as margin-left: 20 px; ). The correct way is: margin-left: 20px; An internal style sheet may be used if one single HTML page has a unique style. The internal style is defined inside the <style> element, inside the head section. Internal styles are defined within the <style

Comments
  • good! but this doesn't check for duplicate values if the class already contains new values to add. So, I post a more complete version here
  • FYI output.Attributes.Remove(existingClass); should be located inside the if statement, otherwise it's trying to remove a null value.
  • existingClass.Value.ToString() won't work because existingClass.Value is of type Microsoft.AspNetCore.Mvc.TagHelpers.TagHelperOutputExtensions.ClassAttributeHtmlContent class.
  • To be precise it will work if there is only one class name. But not for 2 or more, for example <div class="message text" ></div> won't return classes in ToString().
  • My example above with <div../> is not correct. Actually method .ToString() works fine if there were no tag-helpers which added some extra classes via output. Attributes.Add("class", ...) before our tag-helper is invoked. If they did then method .ToString() won't return expected names of css classes. It will return "ClassAttributeHtml‌​Content" C# class name instead in ASP.NET Core 2.
  • Boy oh boy is this UGLY that we have to do it this way. I will be writing an extension method to greatly alleviate this pain, but I wonder why the team can't see the Need for Simplicity® here.