Unable to serialize List<SelectListItem>

asp.net-mvc-3, c#

Solution

Try to create the select list items in the Razor code instead by with a `SelectList`. Let the model instead have a property for the underlying data that the `SelectList` is based on. You may also try to place the `SelectList` in the `ViewBag` or `ViewData`, that could also solve problem.

Storing `SelectList`'s in the view model is regarded as bad practice.

Problem

I'm moving an existing MVC3 app from InProc to ASP.Net Session State service. One of the model objects has this property: ``` public List<System.Web.Mvc.SelectListItem> StateCodes { get; set; } ``` and it's throwing this error Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode. Is there a way to get `List<SelectListItem>` to serialize?

Original source