Problem storing a Generic list object in Viewstate

I had an generic object that implements and I was just trying to store that object in ViewState. THis was where i first stumbled as it was giving me an error that basically tells that “Cannot serialze a generic list object”. After I did a bit of googling I found out that I need to make that object XmlSerializable inoder to be strored in Viewstate.

I used the [serializable ] attribute on the class that I wanted to serialize.

Still i was giving me error. After a quite prolonged step into this problem my senior (read Project Manager) found out a nice cool solution.

I addition to that attribute what he did is as follows.

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Quickly Illustrate  Creation of a List of that contains information;

        List<Customer> CustomerList = new List<Customer>();

        Customer SingleCustomer = new Customer();

        SingleCustomer.CustomerAddress = "my address";

        SingleCustomer.CustomerName = "my name";

        CustomerList.Add(SingleCustomer);

        // Convert the List to Array and Save To View State

        // Rather than Handling Serialization Manually

        ViewState.Add("Customers", CustomerList.ToArray());

        Customer[] newArray = (Customer[])ViewState["Customers"];

        List<Customer> newList = new List<Customer>(newArray);

        Response.Write(CustomerList[0].CustomerName);

    }

    [Serializable]

    public class Customer

    {

        private string _CustomerName = "";

        private string _CustomerAddress = "";

        public string CustomerName

        {

            get

            {

                return _CustomerName;

            }

            set

            {

                _CustomerName = value;

            }

        }

        public string CustomerAddress

        {

            get

            {

                return _CustomerAddress;

            }

            set

            {

                _CustomerAddress = value;

            }

        }

    }

}

This article is part of the GWB Archives. Original Author: Dheeman Dutta

New on Geeks with Blogs