Willy
Willy

Reputation: 10650

Are properties within a Serializable class automatically serialized when inserted on Session object in ASP.NET?

I have an ASP.NET application which uses InProc session state mode. I have a class marked as serializable:

namespace MyNamespace
{
    [Serializable]
    public class MyClass
    {
        public System.Web.Mvc.SelectList myList { get; set; }
    }
}

...Now I have a doubt: When assigning the property value within the serialized class to the session object like below:

Session["MyList"] = InstaceOfMyClass.myList;

... is myList property automatically serialized once inserted to Session["MyList"] object?

In case it is not serialized, how can I serialize it on inserting to Session["MyList"] object? by indicate property with serializable attribute?

Upvotes: 0

Views: 262

Answers (2)

LongChalk_Rotem_Meron
LongChalk_Rotem_Meron

Reputation: 803

Serialization and passing a model (and some extra data) from the controller to the view (as indicated by the System.Web.Mvc.SelectList) are two very different things.

Serialization has to do with turning an object into a string (or binary array) and Deserialization back from a string (or binary array) to an object.

The model passed back and forth on MVC is what the view should render. You're probably looking for a single property in that model (say countryID) to be displayed in a drop down list (or an html <select> or more generally a combo box). This bundle of wrapping data (say - the list of countries - Id and name pairs) should be passed on via a ViewBag or ViewData.

A SelectList should NOT be done on session as storing it is a big waste of memory. It will just linger there in memory long after the user has received his HttpResponse. A select list is just a list of options in the combo box, and as such it is not serializable (although it's content might be). You should really make the distinction between "the data inhabiting the combo box" (thin object) and "the combo box itself" (fat object). In this example - between the countries (which are an IEnumerable), and the UI element. Serializing a UI element doesn't make sense, and should always be avoided.

Upvotes: 1

DavidG
DavidG

Reputation: 119016

If you are talking about in-process only, serialisation doesn't happen, the item is stored as a normal live reference to a .NET object, no serialisation happens.

If your session state is external (e.g. database) then obviously they need to be serialised at that point.

With regards to your specific point, there is no difference between what you are doing and creating the SelectList object manually and passing that into the session.

If I were you, I would strongly recommend that you do not store objects like this in the session, try to keep it to classes that you control (and can mark as Serializable), because if you do need to switch to out-of-process storage, you won't need to re-engineer your code.

Upvotes: 1

Related Questions