1
votes

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+WhereSelectEnumerableIterator2[[System.Collections.Generic.KeyValuePair2[[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?

2
Be careful placing large objects into the session.Yuriy Faktorovich

2 Answers

4
votes

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>;
0
votes

You can cast like below.

var stateSummaries = (List<ModelStateSummary>)Session["ModelStateSummaryModel"];