我有一个类型为List<JobSeeker>
的列表。我想将它存储在ViewState中。如何实现?
private List<JobSeeker> JobSeekersList { get; set; }
基本上您只需要使用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;
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;
}
}
as
еТМ!=null
жѓФis
еТМcast
жЫійЂШжХИгАВ - abatishchevis
不高效 - 我使用它来双重检查对象是否已设置,如果已设置,则必须与我想要的对象相同。这与您提供的页面上的示例不同。 - Aristos