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?
CSS classes can be added to any HTML element.
Class in html:The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size.
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);
...
}
@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}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With