TagBuilder AddCssClass顺序,添加到开头,如何在结尾添加新类? [英] TagBuilder AddCssClass Order, Adds to Beginning, how to Add New Class at the End?

查看:114
本文介绍了TagBuilder AddCssClass顺序,添加到开头,如何在结尾添加新类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Tagbuilder AddCssClass将标签添加到Beginning。

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

在这种情况下,Number2将是第一个。

In this situation, Number2 will be first.

推荐答案

查看代码此处,似乎无法使用您所使用的方法将类添加到最后。 AddCssClass的代码如下所示:

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

对于我们来说,TagBuilder对象公开了属性,因此我们可以编写一个扩展方法,将值添加到末尾而不是开头:

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

这篇关于TagBuilder AddCssClass顺序,添加到开头,如何在结尾添加新类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆