如何将对象列表存储到ViewState中

use*_*523 11 .net c# asp.net viewstate list

我有一个类型列表List<JobSeeker>.我想将它存储在ViewState中.怎么做到这一点?

private List<JobSeeker> JobSeekersList { get; set; }
Run Code Online (Sandbox Code Playgroud)

Ari*_*tos 20

基本上你只需要使用get,然后就可以从视图状态获取发布的数据,或者在视图状态下第一次设置它.这是更强大的代码,可以避免对每个调用进行所有检查(视图状态设置,存在等),并直接保存并使用视图状态对象.

// 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

替代避免 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

JobSeeker类必须[Serializable]

[Serializable]
public class JobSeeker
{
    public int ID;
    ...
}
Run Code Online (Sandbox Code Playgroud)

并且您通常将其简单地称为对象,并且永远不会为null.也会在回发后返回保存在viewstate值上的值

JobSeekersList.add(new JobSeeker(){ID=1});
var myID = JobSeekersList[0].ID;
Run Code Online (Sandbox Code Playgroud)