2012-02-09 2 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

writer 클래스를 확장하고 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>>(); 
    } 
} 
관련 문제