TAGS :Viewed: 18 - Published at: a few seconds ago

[ How to Serialize a ListItem Stored in Session ]

I have this code which works fine on my local server:

if (Page.IsPostBack)
{
    string[] questions = new string[20];
    string[] answers = new string[20];
    for (int i = 0; i < lstQuestions.Items.Count; ++i)
    {
        questions[i] = lstQuestions.Items[i].Text;
        answers[i] = lstQuestions.Items[i].Value;
    }
    Session["questions"] = questions;
    Session["answers"] = answers;
    if (Session["qalist"] == null)
    {
        List<ListItem> qalist = lstQuestions.Items.Cast<ListItem>().ToList();
        Session["qalist"] = qalist;
    }
    else
    {
        List<ListItem> qalist = (List<ListItem>)Session["qalist"];
        lstQuestions.DataSource = qalist;
    }
}

else
{
    if (Session["questions"] != null && Session["answers"] != null && Session["qalist"] != null)
    {
        List<ListItem> qalist = (List<ListItem>)Session["qalist"];
        foreach (ListItem item in qalist)
        {
            lstQuestions.Items.Add(new ListItem(item.Text, item.Value.ToString()));
        }
    }
}

However, when I go to the web server, I get the error "System.Web.UI.WebControls.ListItem, not marked as serializable". I've looked into how I can make this serializable, or even how to convert "qalist" to a value that is in fact serializable, and then save that value to a session. However, my efforts were to no avail. Would serializing be the best route? Finding a different way to store this data? Or something else?

Answer 1


System.Web.UI.WebControls.ListItem is not serializable, as you have observed. Thus you can't store it in session.

I'm a little confused why you're saving the two data properties of the ListItem - questions and answers - separately into Session, and also the ListItem itself. It looks to me that, having questions and answers, you have all you need to reconstruct a ListItem.

But if you want to save your question and answer together as a pair, you could use a List<T> of System.Tuple<string, string>, which is serializable, or even System.Web.UI.Pair, which is also serializable.

You could also write your own (very simple) class, and mark it as serializable:

[Serializable]
public class QuestionAndAnswer
{
    public string Question { get; set;}
    public string Answer { get; set; }
}

Answer 2


You can try use JSON.Net (Newtonsoft) to do the serialization and deserialization.

To serialize

Session["qalist"] = JsonConvert.SerializeObject(lstQuestions);

To deserialize (T is the type of lstQuestions)

lstQuestions = JsonConvert.DeserializeObject<T>(Session["qalist"]);

I hope it help