如何存储对象的名单到ViewState中 [英] How to store list of object into ViewState

查看:207
本文介绍了如何存储对象的名单到ViewState中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类型的列表名单,其中,求职者> 。我想将其存储在ViewState中。这可怎么办呢?

 私人列表<求职者> JobSeekersList {获得;组; }
 

解决方案

基本上你只需要使用 GET

  //使用这个常量你避免错误的mispelling正确的密钥。
常量字符串cJobSeekerNameConst =JobSeeker_cnst;

公开名单<求职者> JobSeekersList
{
    得到
    {
        如果(!(的ViewState [cJobSeekerNameConst]是列表<求职者>))
        {
            //需要修复的内存,并添加到视图状态
            的ViewState [cJobSeekerNameConst] =新的名单,其中,求职者>();
        }

        返回(名单<求职者>)的ViewState [cJobSeekerNameConst]
    }
}
 

求职者类必须是 [Serializable接口]

  [Serializable接口]
公共类求职者
{
    ...
}
 

替代,以避免

 公开名单<求职者> JobSeekersList
{
    得到
    {
        //如果不是在视图状态然后将其添加
        如果(的ViewState [cJobSeekerNameConst] ==​​ NULL)
            的ViewState [cJobSeekerNameConst] =新的名单,其中,求职者>();

        //这个code未获释存在,但我检查,以确保我没有
        //覆盖此视图状态具有不同的对象。
        Debug.Assert的(的ViewState [cJobSeekerNameConst]是列表<求职者>);

        返回(名单<求职者>)的ViewState [cJobSeekerNameConst]
    }
}
 

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; }

解决方案

Basically you only need to use the get as

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

public List<JobSeeker> JobSeekersList
{
    get
    {
        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];
    }
}

and the JobSeeker class must be [Serializable] as

[Serializable]
public class JobSeeker
{
    ...
}

Alternative to avoid the is

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];
    }
}

这篇关于如何存储对象的名单到ViewState中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆