Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 814
Steven Zack Avatar asked Sep 27 '11 20:09

Steven Zack


People also ask

What kind of data we can store in ViewState?

Because the data in viewstate is stored as a string, only objects that can be serialized can be stored.. Yes. We can store object in ViewState as it stores the data in the string form although it works like dictionary. Just serialize the object and store the string in ViewState.

What is view state and how it works in asp net?

View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. View State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back.


3 Answers

You are storing string and expecting ItemId. You should store as

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

However, since ItemId is not seriaziable, it cannot be stored. To store it make your serializable class inherited from ItemId and override all the members and store it in ViewState

[Serializable]
public class MyItemId: ItemId {
 // override all properties 
}

Store like this

MyItemId itemId = new MyItemId();
ViewState["itemId"] = itemId;

and retrieve

MyItemId id=(MyItemId)ViewState["itemId"];
like image 114
hungryMind Avatar answered Nov 11 '22 13:11

hungryMind


Did you try:

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

http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.itemid.itemid(EXCHG.80).aspx

like image 41
Wiktor Zychla Avatar answered Nov 11 '22 13:11

Wiktor Zychla


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?

like image 27
Luke Girvin Avatar answered Nov 11 '22 14:11

Luke Girvin