TagBuilder AddCssClass Order, Adds to Beginning, h

2019-07-26 09:07发布

问题:

I noticed Tagbuilder AddCssClass adds tags to the Beginning. How do I make it add it to the end.

TagBuilder test = new TagBuilder("div");
toolset.AddCssClass("Number1");
toolset.AddCssClass("Number2");

In this situation, Number2 will be first.

回答1:

Looking at the code here, it doesn't seem like it's possible to add the class onto the end using the method that you are. The code for AddCssClass looks like this:

public void AddCssClass(string value)
{
    string currentValue;

    if (Attributes.TryGetValue("class", out currentValue))
    {
        Attributes["class"] = value + " " + currentValue;
    }
    else
    {
        Attributes["class"] = value;
    }
}

Fortunately for us, the TagBuilder object exposes Attributes, so we can write an extension method which adds the value to the end rather than the beginning:

public static class TagBuilderExtensions
{
    public void AddCssClassEnd(this TagBuilder tagBuilder, string value)
    {
        string currentValue;

        if (tagBuilder.Attributes.TryGetValue("class", out currentValue))
        {
            tagBuilder.Attributes["class"] = currentValue + " " + value;
        }
        else
        {
            tagBuilder.Attributes["class"] = value;
        }
    }
}

And provided you have a using for the namespace you define the above extension method in, you can simply use it like so:

toolset.AddCssClassEnd("Number1");