0

有谁知道如何将自定义控件序列化为从另一个 Web 控件派生的 JSON。我不断收到基类不可序列化的错误。这是派生类的代码

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 类不可序列化。

4

1 回答 1

1

在 DataContractJsonSerializer 上,您可以定义一个替代控件进行序列化的代理(搜索 IDataContractSurrogate 以获取更多信息)。但是,如果您只需要序列化这两个属性,那么简单地使用这些属性创建一个数据类(DTO?)并将其序列化可能会更简单。

public class BaseWidgetDTO
{
    public int ControlID { get; set; }
    public string Title { get; set; }
}
于 2011-05-24T19:57:48.557 回答