将CSS类添加到TagHelper中的html元素

时间:2016-10-26 17:23:50

标签: c# asp.net-core tag-helpers

在ASP.NET核心视图中,我有以下内容:

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

我是一个带有以下TagHelper的Tag Helper:

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

在以下代码行中,我需要添加&#34; active&#34;作为CSS类。

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

然而,这没有任何作用。消息仅保留在课程&#34;消息&#34;。

我错过了什么?

4 个答案:

答案 0 :(得分:12)

从ASP.NET Core 2.1开始,您可以使用Microsoft提供的TagHelperOutputExtensions类在一行代码中添加“活动” CSS类。

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

答案 1 :(得分:5)

@ Shyju的回答大多是正确的,但是有很多无关的代码是不必要的。以下内容足以在ASP.NET Core 2.0中处理它:

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

答案 2 :(得分:2)

我认为您应该从Attributes集合中删除现有的TagHelperAttribute css类,并添加一个包含所有类的新类(Existing和您的新&#34; active&#34; class)

以下代码应该有效。

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

答案 3 :(得分:1)

这里的其他答案不检查当前的css类,以避免重复的值。在这里,我编写了一个扩展以添加带有适当检查的css类,以确保输出的HTML干净:

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

    }

}