我一直在使用这里引用的优秀帖子: How to access session variables from any class in ASP.NET?
但是,我想在会话中存储自定义对象类型,但是我在构造对象会话类时遇到了问题。在会话中,我想存储一个SchoolID和Grade对列表。 SchoolID-Grade对象如下所示:
[Serializable]
public class SchoolGrade
{
public string SchoolID { get; set; }
public string Grade { get; set; }
public SchoolGrade(string SchoolID, string Grade)
{
this.SchoolID = SchoolID;
this.Grade = Grade;
}
}
会话包装器如下,我得到了一个"空引用"构造函数出错。
public class EventSchoolsAndGradesSession
{
#region " Properties "
public List<SchoolGrade> schoolgrade { get; set; }
#endregion
#region " Constructors "
private EventSchoolsAndGradesSession()
{
schoolgrade.Add(new SchoolGrade("0", "0"));
}
#endregion
#region " Methods "
public static EventSchoolsAndGradesSession Current
{
get
{
EventSchoolsAndGradesSession session = (EventSchoolsAndGradesSession)HttpContext.Current.Session["_EventStudentSchoolAndGrade_"];
if (session == null)
{
session = new EventSchoolsAndGradesSession();
HttpContext.Current.Session["_EventStudentSchoolAndGrade_"] = session;
}
return session;
}
}
#endregion
}
我的目标是能够在会话中添加和删除特定的SchoolID和成绩对。例如,这将采用会话中存在的对,将它们添加到临时列表,将新对添加到临时列表,然后将所有对保存回会话:
protected void AddAllButton_Click(object sender, EventArgs e)
{
List<SchoolGrade> selected = new List<SchoolGrade>();
var current = EventSchoolsAndGradesSession.Current.schoolgrade.ToList();
if (current != null)
{
foreach (SchoolGrade s in current)
{
selected.Add(new SchoolGrade(s.SchoolID,
s.Grade));
}
}
selected.Add(new SchoolGrade(SchoolsDropDownList.SelectedValue,
GradeDropDownList.SelectedValue));
EventSchoolsAndGradesSession.Current.schoolgrade = selected.ToList();
}
有人可以指出我做错了吗?
答案 0 :(得分:1)
您正在尝试将新项目添加到该构造函数中的未初始化列表
尝试
#region " Constructors "
private EventSchoolsAndGradesSession()
{
schoolgrade = new List<SchoolGrade>();
schoolgrade.Add(new SchoolGrade("0", "0"));
}