Reputation: 22212
I have a list to store in session in SqlServer mode.
[Serializable]
public class ModelStateSummary
{
public string PropertyName { get; set; }
public string[] ErrorMessages { get; set; }
}
Set the session
var list = new List<ModelStateSummary> {...};
Session["ModelStateSummaryModel"] = list;
But when I tried to retrieve the model from the session
var stateSummaries = Session["ModelStateSummaryModel"] as IEnumerable<ModelStateSummary>;
I got an error, saying,
Exception type: System.Runtime.Serialization.SerializationException Exception message: Type 'System.Linq.Enumerable+WhereSelectEnumerableIterator
2[[System.Collections.Generic.KeyValuePair
2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Web.Mvc.ModelState, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[myproject.ModelStateSummary, myproject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Have I done something wrong in saving the list into Session?
Upvotes: 1
Views: 4611
Reputation: 4130
When you put the object in the Session, it is serialized there. This also means that non-serializable objects cannot be stored there. Then when you get it out of the session, it gets deserialized. You can't deserialize to an interface. It must be a concrete class.
var stateSummaries = Session["ModelStateSummaryModel"] as List<ModelStateSummary>;
Upvotes: 5
Reputation: 48367
You can cast
like below.
var stateSummaries = (List<ModelStateSummary>)Session["ModelStateSummaryModel"];
Upvotes: 0