简体   繁体   中英

Getting serialization exception when storing a list of object to session variable

I have a form which I want to store input field values to session variables. The form is used to create new user: an admin user would put in an username of new user, go to next page to add other info, and then create the user. So, I want to store the info they put on the first page to session variables to be able to use it later. Problem is that I'm getting a serialization exception.

This is the ajax I'm using, when going from first page to second page:

function holdUserData() {
    //pass in username and a list of club IDs
    var data = {
        username: $('#tbUsername').val(), 
        clubs: this.clubs
    };

    $.ajax({
        type: "POST",
        url: '/Users/GoManageClub', //store in GoManageClub controller
        data: data,
        success: function (data) {
            //redirect to ManageClubAccess controller when done
            window.location = '/Users/ManagClubAccess';
        }
    })
}

And my GoManageClub controller, storing the data to session:

[HttpPost]
public ActionResult GoManagePolicy(string username, List<ClubVM> clubs)
{
    Session["Username"] = username;
    Session["Clubs"] = clubs;

    return this.Json(new { success = true });
}

When I only store the username string, there are no problems and the variable is successfully stored. But when I'm storing the List<ClubVM> , I get the serialization exception:

Type 'myOrganization.ClubVM' in Assembly 'myorg, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable

My ClubVM :

public class ClubVM
{
    public int ID { get; set; }
    /* ... */
}

What should I do so I can save List<ClubVM> clubs ?

The class to be serialized needs a Serializable attribute.

This indicates that you intend for the class to be serialized (stored as set of bytes.) That's what happens when you save an object to Session . Depending on the implementation of Session the object could be stored in memory or it could be saved to a database.

[Serializable()]
public class ClubVM
{
    public int ID { get; set; }
    /* ... */
}

Value types like int are already serializable. But if ClubVM contains references to other types then those types must also be serializable unless you mark them with a NonSerialized attribute. And so on. But if you mark something NonSerialized that means that when you deserialize the object (retrieve it from Session ) that property will be missing because it wasn't included when the rest of the object was serialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM