TagBuilder AddCssClass Order, Adds to Beginning, how to Add New Class at the End?

自闭症网瘾萝莉.ら 提交于 2019-12-11 15:51:24

问题


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


来源:https://stackoverflow.com/questions/57105604/tagbuilder-addcssclass-order-adds-to-beginning-how-to-add-new-class-at-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!