views:

108

answers:

2

I have added one datalist into view state as:

ViewState["datalist"] = dtlstForm;

and retrieved it as:

DataList lis = (DataList)ViewState["datalist"];

then folowing error comes:

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

+1  A: 

You can't put an object in the viewstate unless it implements ISerializable. The viewstate is serialised before it is sent to the client.

You can use Session in a similar way to viewstate and for all intents and purposes it will be ok. Session I would presume is more resource hungry.

Is datalist your own class? If so you could implement ISerializable as well but I wouldn't go down that route if I could just type session instead.

Robert
DataList = System.Web.UI.WebControls.DataList, so not the OP's own class.
Paul Alan Taylor
SessionState will work only if it is set to InProc (in process) and held in the applications memory. If you are using a state server or Sql server to hold your session state then any objects held in session will also need to be serializable.
Andy Rose
+1  A: 

The DataList class is not serializable (the SerializableAttibute has not be set on it and it is not implementing the ISerializable interface).

This mean the .NET framework cannot serialize it and put it into ViewState.

Since this is a built in class, you cannot modify it to be serializable.

As a DataList is expected to hold quite a lot of information, putting it in ViewState would cause ViewState to be huge, which would impact performance, so it makes sense to not make it serializable.

Perhaps you can rethink the information you need to put in ViewState and only put a small amount into it (a list of IDs for example).

Oded