13

我有一个 type 列表List<JobSeeker>。我想将它存储在 ViewState 中。如何做到这一点?

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

2 回答 2

23

基本上你只需要使用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];
    }
}

避免的替代方案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];
    }
}

并且JobSeeker课程必须[Serializable]

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

并且您通常将其简单地称为对象,并且永远不会为空。回发后也将返回保存的视图状态值

JobSeekersList.add(new JobSeeker(){ID=1});
var myID = JobSeekersList[0].ID;
于 2012-11-18T05:56:43.783 回答
2
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;
    }
}
于 2012-11-18T06:27:48.383 回答