Search code examples
c#asp.netviewstate

How to store an object in the viewstate?


I am using EWS to develop my email client. I found that if I store ItemId in viewstate it will cause an exception says:

Type 'Microsoft.Exchange.WebServices.Data.ItemId' in Assembly 'Microsoft.Exchange.WebServices, Version=14.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

If I store ItemId as string like:

ViewState["itemId"] = id.ToString();

and then try to cast back,

ItemId id = (ItemId)ViewState["itemId"];

it says I can not convert from string to ItemId. Any idea?


Solution

  • As the error message suggests, you can't store an object in viewstate unless it's marked as serializable.

    Looking at the documentation here, it seems that the ItemId class has a UniqueId property, which is a string, and a constructor which takes a string 'uniqueId' parameter.

    So, can you store the uniqueId in viewstate, and regenerate the object using the constructor?