How to store list of object into ViewState

user1613523 picture user1613523 · Nov 18, 2012 · Viewed 38.2k times · Source

I have a list of type List<JobSeeker>. I want to store it in ViewState. How this can be done?

private List<JobSeeker> JobSeekersList { get; set; }

Answer

Aristos picture Aristos · Nov 18, 2012

Basically you only need to use the get , then on get you either get the posted data from view state, or set it for the first time on the view state. This is the more robust code to avoid all the checks on each call (is view state set, exist etc), and direct saved and use the view state object.

// using this const you avoid bugs in mispelling the correct key.
const string cJobSeekerNameConst = "JobSeeker_cnst";

public List<JobSeeker> JobSeekersList
{
    get
    {
        // check if not exist to make new (normally before the post back)
        // and at the same time check that you did not use the same viewstate for other object
        if (!(ViewState[cJobSeekerNameConst] is List<JobSeeker>))
        {
            // need to fix the memory and added to viewstate
            ViewState[cJobSeekerNameConst] = new List<JobSeeker>();
        }

        return (List<JobSeeker>)ViewState[cJobSeekerNameConst];
    }
}

Alternative to avoid the is

// using this const you avoid bugs in mispelling the correct key.
const string cJobSeekerNameConst = "JobSeeker_cnst";

public List<JobSeeker> JobSeekersList
{
    get
    {
        // If not on the viewstate then add it
        if (ViewState[cJobSeekerNameConst] == null)                
            ViewState[cJobSeekerNameConst] = new List<JobSeeker>();

        // this code is not exist on release, but I check to be sure that I did not 
        //  overwrite this viewstate with a different object.
        Debug.Assert(ViewState[cJobSeekerNameConst] is List<JobSeeker>);

        return (List<JobSeeker>)ViewState[cJobSeekerNameConst];
    }
}

and the JobSeeker class must be [Serializable] as

[Serializable]
public class JobSeeker
{
    public int ID;
    ...
}

and you simple call it normally as an object and will never be null. Also will be return the saved on viewstate values after the post back

JobSeekersList.add(new JobSeeker(){ID=1});
var myID = JobSeekersList[0].ID;