Add CSS Class to html element in a TagHelper

Miguel Moura picture Miguel Moura · Oct 26, 2016 · Viewed 8.5k times · Source

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?

Answer

Mathew Leger picture Mathew Leger · Aug 23, 2018

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);
    ...
}