3

使用 HtmlTextWriter 向标签添加多个类的最佳方法是什么?

我想做的是......

 writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class1");
 writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class2");
 writer.RenderBeginTag(HtmlTextWriterTag.Table);

导致...

<table class="Class1 Class2">

我很感激我能做到...

writer.AddAttribute(HtmlTextWriterAttribute.Class, "Class1 Class2");

然而,动态构建控件时并不总是这么简单。是否有其他方法可以将类“附加”到标签?

4

2 回答 2

6

为什么不扩展 writer 类并在其上添加 AddClass 和 RemoveClass 方法,渲染时使用所有添加的类名。在内部,您可以使用 List _classNames 来保存然后加入它们

writer.AddAttribute(HtmlTextWriterAttribute.Class,string.Join(_classNames.ToArray(), "");

希望有帮助!

于 2012-02-09T10:57:26.170 回答
2

只是按照上一个帖子的想法......

public class NavHtmlTextWritter : HtmlTextWriter
{
    private Dictionary<HtmlTextWriterAttribute, List<string>> attrValues = new Dictionary<HtmlTextWriterAttribute, List<string>>();
    private HtmlTextWriterAttribute[] multiValueAttrs = new[] { HtmlTextWriterAttribute.Class };

    public NavHtmlTextWritter (TextWriter writer) : base(writer) { } 

    public override void AddAttribute(HtmlTextWriterAttribute key, string value)
    {
        if (multiValueAttrs.Contains(key))
        {
            if (!this.attrValues.ContainsKey(key))
                this.attrValues.Add(key, new List<string>());

            this.attrValues[key].Add(value);
        }
        else
        {
            base.AddAttribute(key, value);
        }
    }

    public override void RenderBeginTag(HtmlTextWriterTag tagKey)
    {
        this.addMultiValuesAttrs();
        base.RenderBeginTag(tagKey);
    }

    public override void RenderBeginTag(string tagName)
    {
        this.addMultiValuesAttrs();
        base.RenderBeginTag(tagName);
    }

    private void addMultiValuesAttrs()
    {
        foreach (var key in this.attrValues.Keys)
            this.AddAttribute(key.ToString(), string.Join(" ", this.attrValues[key].ToArray()));

        this.attrValues = new Dictionary<HtmlTextWriterAttribute, List<string>>();
    }
}
于 2012-07-10T05:58:53.033 回答