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

ライタークラスを拡張し、レンダリング中に追加されたすべてのクラス名を使用する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 に答える