[c#] Error - is not marked as serializable

The error I'm getting is:

Type 'OrgPermission' in Assembly 'App_Code.ptjvczom, Version=, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 

here is my code:

I have a gridview, that uses the following DataSource:

 <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetOrgList" 
      <asp:SessionParameter Name="orgCodes" SessionField="UserOrgs" Type="Object" />
       <asp:Parameter DefaultValue="Y" Name="active" Type="String" />

I set the session variable in my page load like so:

User cUser = new User(userid);
//make sure the user is an Admin
List<OrgPermission> orgs = new List<OrgPermission>();
foreach(OrgPermission org in cUser.orgs)
     if (org.type=='admin')
Session["UserOrgs"] = orgs;

My user class looks like this:

public class OrgPermission
    public string Org { get; set; }   
    public List<string> type { get; set; }

    public OrgPermission()
    { }    
public class cUser
    public string userid { get; set; }
    public List<OrgPermission> orgs { get; set; }

    public clsUser(string username)
      //i set everything here

I can't understand why it's breaking, can I use it without making it serializable?

I tried to debug, and the session variable sets just fine, it then goes into the GetOrgList and returned correct results, but the page does not load and I get the error above.

Here is a snippet of my GetOrgList function:

public DataTable GetOrgList(List<OrgPermission> orgCodes, string active)

        string orgList = null;

        //code to set OrgList using the parameter is here.

        DataSet ds = new DataSet();
        SqlConnection conn = new SqlConnection(cCon.getConn());
        SqlCommand cmd = new SqlCommand("sp_GetOrgList", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@orgList", orgList));
        cmd.Parameters.Add(new SqlParameter("@active", active));

            SqlDataAdapter sqlDA = new SqlDataAdapter();

            sqlDA.SelectCommand = cmd;

        return ds.Tables[0];

This question is related to c# asp.net .net serialization

The answer is

You need to add a Serializable attribute to the class which you want to serialize.

public class OrgPermission

If you store an object in session state, that object must be serializable.



In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.


Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

Questions with c# tag:

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with asp.net tag:

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version= No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Custom Authentication in ASP.Net-Core Custom header to HttpClient request ASP.NET 5 MVC: unable to connect to web server 'IIS Express' IIS Config Error - This configuration section cannot be used at this path Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015 TLS 1.2 in .NET Framework 4.0 The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default Adding ASP.NET MVC5 Identity Authentication to an existing project TypeError: $(...).DataTable is not a function The page cannot be displayed because an internal server error has occurred on server How to get the current logged in user Id in ASP.NET Core When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 No connection could be made because the target machine actively refused it @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How can I validate google reCAPTCHA v2 using javascript/jQuery? How to get DropDownList SelectedValue in Controller in MVC How do I enable NuGet Package Restore in Visual Studio? Specified cast is not valid? Display two fields side by side in a Bootstrap Form variable is not declared it may be inaccessible due to its protection level An unhandled exception occurred during the execution of the current web request. ASP.NET How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception System.web.mvc missing How to get JSON object from Razor Model object in javascript SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance How to get current domain name in ASP.NET How to return a file (FileContentResult) in ASP.NET WebAPI Select query to get data from SQL Server NuGet: 'X' already has a dependency defined for 'Y' How can I make window.showmodaldialog work in chrome 37? Selecting multiple columns with linq query and lambda expression onchange event for html.dropdownlist Pass multiple complex objects to a post/put Web API method How to update a claim in ASP.NET Identity?

Questions with .net tag:

You must add a reference to assembly 'netstandard, Version= How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface How to decode JWT Token? What's the difference between .NET Core, .NET Framework, and Xamarin? .NET Core vs Mono How to specify the port an ASP.NET Core application is hosted on? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests Build error, This project references NuGet IIS Config Error - This configuration section cannot be used at this path There is no argument given that corresponds to the required formal parameter - .NET Error Could not find a part of the path ... bin\roslyn\csc.exe Can you install and run apps built on the .NET framework on a Mac? What is the purpose of nameof? Microsoft.ReportViewer.Common Version= What is the default value for Guid? Authentication failed because remote party has closed the transport stream What is the difference between a Shared Project and a Class Library in Visual Studio 2015? How to break out of the IF statement No connection could be made because the target machine actively refused it Default SecurityProtocol in .NET 4.5 How to properly make a http web GET request What is ".NET Core"? IOException: The process cannot access the file 'file path' because it is being used by another process System.web.mvc missing Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation) SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) Write to Windows Application Event Log Operator overloading ==, !=, Equals System.Net.WebException: The remote name could not be resolved: Running multiple async tasks and waiting for them all to complete What is an "index out of range" exception, and how do I fix it? Found conflicts between different versions of the same dependent assembly that could not be resolved Getting the first and last day of a month, using a given DateTime object Error 1053 the service did not respond to the start or control request in a timely fashion BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed Download files from SFTP with SSH.NET library An object reference is required to access a non-static member AppendChild() is not a function javascript Send JSON via POST in C# and Receive the JSON returned? Why is HttpClient BaseAddress not working? KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

Questions with serialization tag:

laravel Unable to prepare route ... for serialization. Uses Closure TypeError: Object of type 'bytes' is not JSON serializable Best way to save a trained model in PyTorch? Convert Dictionary to JSON in Swift Java: JSON -> Protobuf & back conversion Understanding passport serialize deserialize How to generate serial version UID in Intellij Parcelable encountered IOException writing serializable object getactivity() Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty? Cannot deserialize the current JSON array (e.g. [1,2,3]) Simple working Example of json.net in VB.net Entity framework self referencing loop detected Converting Stream to String and back...what are we missing? Java ByteBuffer to String How to write and read java serialized objects into a file <Django object > is not JSON serializable Form submit with AJAX passing form data to PHP without page refresh .NET NewtonSoft JSON deserialize map to a different property name Error - is not marked as serializable Serializing and submitting a form with jQuery and PHP Why does writeObject throw java.io.NotSerializableException and how do I fix it? Exception: Serialization of 'Closure' is not allowed JSON.Net Self referencing loop detected IntelliJ IDEA generating serialVersionUID Jackson JSON custom serialization for certain fields NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> Jackson - How to process (deserialize) nested JSON? form serialize javascript (no framework) @JsonProperty annotation on field as well as getter/setter Convert an object to an XML string Java to Jackson JSON serialization: Money fields Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class jQuery: serialize() form and other parameters Serializing/deserializing with memory stream java.io.InvalidClassException: local class incompatible: Serializing class instance to JSON How to repair a serialized string which has been corrupted by an incorrect byte count length? How can I change property names when serializing with Json.net? Json.net serialize/deserialize derived types? Java serialization - java.io.InvalidClassException local class incompatible How to JSON serialize sets? Can Json.NET serialize / deserialize to / from a stream? JSON.NET Error Self referencing loop detected for type How do I use a custom Serializer with Jackson? Converting between strings and ArrayBuffers Deserialize JSON array(or list) in C# $(this).serialize() -- How to add a value? Best way to serialize/unserialize objects in JavaScript?