2011-05-24 62 views
0

有誰知道如何將自定義控件序列化爲從其他Web控件派生的JSON。我不斷收到基類不可序列化的錯誤。下面是派生類如何JSON序列化派生自Web控件類的類

public class BaseWidget : CompositeControl 
{ 
    protected Label _lblHeader; 
    protected Button _editButton; 
    protected HtmlInputHidden _idField; 

    /// <summary> 
    /// The Unique identified that identifies this widget 
    /// </summary> 

    public int ControlID 
    { 
     get 
     { 
      EnsureChildControls(); 
      int i = -1; 
      int.TryParse(_idField.Value, out i); 
      return i; 
     } 
     set 
     { 
      EnsureChildControls(); 
      _idField.Value = value.ToString(); 
     } 
    } 

    /// <summary> 
    /// Allow the user to edit the widget 
    /// </summary> 
    public bool AllowEdit 
    { 
     get; 
     set; 
    } 


    public string Title 
    { 
     get 
     { 
      EnsureChildControls(); 
      return _lblHeader.Text; 
     } 
     set 
     { 
      EnsureChildControls(); 
      _lblHeader.Text = value; 
     } 
    } 



    public string CallbackFunction 
    { 
     get; 
     set; 
    } 


    protected Panel Header 
    { 
     get; 
     set; 
    } 

    /// <summary> 
    /// The Main Control of the widget 
    /// </summary> 
    protected Panel Content 
    { 
     get; 
     set; 
    } 

    protected Panel Edit 
    { 
     get; 
     set; 
    } 

    protected Panel Body 
    { 
     get; 
     set; 
    } 

    /// <summary> 
    /// The tag that the control is associated with 
    /// </summary> 
    protected override HtmlTextWriterTag TagKey 
    { 
     get 
     { 
      return HtmlTextWriterTag.Li; 
     } 
    } 


    public BaseWidget() 
    { 
     this.ControlID = 0; 
    }} 

其實我也不需要任何序列化的屬性的基類的代碼。我只需要控制ID和標題相關的序列化。當Web控件不可序列化時,有沒有這樣做的方法。我試過DataContractJsonSerializer和JavascriptSerializer,因爲WebControl類不是可序列化的。

回答

1

在DataContractJsonSerializer上,您可以定義代替控件的序列化代理程序(有關更多信息,請搜索IDataContractSurrogate)。但是,如果您只需要序列化這兩個屬性,那麼使用這些屬性簡單地創建數據類(DTO?)並將其序列化就可能更簡單。

public class BaseWidgetDTO 
{ 
    public int ControlID { get; set; } 
    public string Title { get; set; } 
} 
+0

+1用於推薦數據傳輸對象(DTO)。 – Sumo 2011-07-10 03:06:46