2012-02-09 69 views
1

使用HtmlTextWriter向標記中添加多個類的最佳方法是什麼?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"); 

但是,動態構建控件時並不總是這樣簡單。是否有其他方法「追加」類到標籤?

回答

3

爲什麼不擴展編寫器類並在其上添加AddClass和RemoveClass方法,該方法在呈現時使用所有添加的類名稱。在內部,你可以使用一個列表_classNames持有再後來又剛剛加入他們

writer.AddAttribute(HtmlTextWriterAttribute.Class,的string.join(_classNames.ToArray(),「「);

希望幫助

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