0

我一直在使用这里引用的优秀帖子: 如何从 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 和 Grade 对。例如,这将获取会话中存在的对,将它们添加到临时列表中,将新对添加到临时列表中,然后将所有内容保存回会话:

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

有人可以指出我做错了什么吗?

4

1 回答 1

1

您正在尝试将新项目添加到该构造函数中的未初始化列表

尝试

#region " Constructors "
private EventSchoolsAndGradesSession()
{
    schoolgrade = new List<SchoolGrade>();
    schoolgrade.Add(new SchoolGrade("0", "0"));
}
于 2013-05-24T21:54:41.853 回答