How to store list of object into ViewState

前端 未结 2 1715
闹比i
闹比i 2020-12-06 10:46

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

private List JobSeekersList         


        
相关标签:
2条回答
  • 2020-12-06 11:15
    private IList<JobSeeker> JobSeekersList
    {
        get
        {
            // to do not break SRP it's better to move check logic out of the getter
            return ViewState["key"] as List<JobSeeker>;
        }
        set
        {
            ViewState["key"] = value;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 11:19

    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;
    
    0 讨论(0)
提交回复
热议问题