How to store an object in the viewstate?

爱⌒轻易说出口 提交于 2019-12-05 19:16:18

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?

hungryMind

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"];

You cannot store it in ViewState.

However you could probably store it in Session, since it uses the binary formatter.

ViewState is serialized with the LosFormatter class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!