HtmlTextWriter - 向标记添加多个类

时间:2012-02-09 09:56:27

标签: c# asp.net class htmltextwriter addattribute

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

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

2 个答案:

答案 0 :(得分:3)

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

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

希望有所帮助!

答案 1 :(得分:1)

按照之前的帖子想法......

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