2011-08-31 118 views
1

我創建了一個自定義ASP.NET控件將作爲容器作用與特定的包裝標籤:從顯示在自定義屬性防止ASP.NET控件屬性

class Section : System.Web.UI.HtmlControls.HtmlGenericControl 
{ 
    public string WrapperTag // Simple interface to base-class TagName 
    { 
     get { return base.TagName; } 
     set { base.TagName = value; } 
    } 


    public string BodyStyle 
    { 
     get 
     { 
      object o = ViewState["BodyStyle"]; 
      return (o == null) ? "" : (string)o; 
     } 
     set 
     { 
      ViewState["BodyStyle"] = value; 
     } 
    } 

    protected override void Render(System.Web.UI.HtmlTextWriter writer) 
    { 
     Attributes["style"] = BodyStyle + ";"; 
     base.Render(writer); 
    } 
} 

這工作沒有問題,但出於某種原因,BodyStyle屬性也顯示爲HTML輸出中的一個屬性。所以,如果我使用控制:

<xx:Section runat="server" WrapperTag="div" BodyStyle="background-color:#ffeeaa;"><other stuff /></xx:Section> 

此輸出:

<div BodyStyle="background-color:#ffeeaa;" style="background-color:#ffeeaa;"><other stuff HTML output /></div> 

我試圖產生輸出:

<div style="background-color:#ffeeaa;"><other stuff HTML output /></div> 

我的問題:

  • 爲什麼BodyStyle顯示爲HTML屬性?
  • 由於出現BodyStyle,爲什麼不出現WrapperTag

回答

1

BodyStyle被寫出,因爲它存在於ViewState中。在OnRender期間,HtmlGenericControl將所有ViewState項添加爲屬性。 WrapperTag不在ViewState中,因此不會寫入屬性。 _bag是StateBag。

下面是從反射器的渲染屬性的實現:

public void Render(HtmlTextWriter writer) 
{ 
    if (this._bag.Count > 0) 
    { 
     IDictionaryEnumerator enumerator = this._bag.GetEnumerator(); 
     while (enumerator.MoveNext()) 
     { 
      StateItem stateItem = enumerator.Value as StateItem; 
      if (stateItem != null) 
      { 
       string text = stateItem.Value as string; 
       string text2 = enumerator.Key as string; 
       if (text2 != null && text != null) 
       { 
        writer.WriteAttribute(text2, text, true); 
       } 
      } 
     } 
    } 
} 

更改您的代碼如下:

private string bodyStyle; 

public string BodyStyle 
{ 
    get 
    { 
     return bodyStyle ?? string.Empty; 
    } 
    set 
    { 
     bodyStyle = value; 
    } 
}