gpt4 book ai didi

c# - 如何将对象列表存储到 ViewState

转载 作者:可可西里 更新时间:2023-11-01 08:37:15 25 4
gpt4 key购买 nike

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

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

最佳答案

基本上你只需要使用 get ,然后你要么从 View 状态获取发布的数据,要么在 View 状态上第一次设置它。这是更健壮的代码,可以避免对每次调用进行所有检查(是否设置 View 状态、是否存在等),并直接保存和使用 View 状态对象。

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

避免的替代方法是

// 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] as

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

并且您通常将其作为对象简单地调用,并且永远不会为空。也将在回发后返回保存的 View 状态值

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

关于c# - 如何将对象列表存储到 ViewState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com