Search code examples
asp.netobjectviewstate

How to add Dictionary of class objects in to view state


I'm having a [Serializable] class with some properties,methods and some web controls. Using this class i were made a Dictionary<string,object> variable. This Dictionary variable contains various objects of my class. Now i need to store this Dictionary variable into view-state so that i can use this Dictionary variable on every post-back of my web form. When i use this line of code to store my Dictionary variable into view-state

ViewState[this.ClientID + "_CtrAdd"] = dictControl;

It throws error:

Type 'System.Web.UI.WebControls.TextBox' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.

Note:

My class objects contains some web controls.

Can any one tell me how can i store this Dictionary variable into an View-state .


Solution

  • As the error suggests, you can't store certain classes, i.e. those that aren't marked as serializable, in ViewState. This is because ViewState is stored as a BASE64-encoded string in a hidden field on the page, and as such any class that you attempt to store in ViewState must be serializable.

    You would have more success building a separate class that just stores data that you need to store in order to have it available in the next postback.

    Web controls will store data in view state without you needing to do anything, so perhaps your class can just store the control's ID which you can then use to reference the control later on.

    For example:

    [Serializable]
    class MyCustomData
    {
        public string TextBoxID1 { get; set; }
        public int MyCounter { get; set;}
        public decimal MyTotal { get; set; }
    }
    
    var data = new MyCustomData { TextBoxID1 = txtMyTextBox.ID, MyCounter = anInt, MyTotal = aDecimal };
    ViewState[this.ClientID + "_Data"] = data;