Domanda

I have been using the excellent post referenced here: How to access session variables from any class in ASP.NET?

However, I want to store a custom object type in the session, but I'm having trouble constructing the object session class. In the session, I want to store a list of SchoolID and Grade pairs. The SchoolID-Grade object looks like this:

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

The session wrapper follows, I'm getting a "Null Reference" error on the constructor.

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
}

My goal is to be able to add and remove specific SchoolID and Grade pairs to the session. for instance this would take pairs that exist in the session, add them to a temp list, add a new pair to the temp list, then save all back to the session:

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

Can someone please point out what I've done wrong?

È stato utile?

Soluzione

You're attempting to add a new item to an uninitialized List in that constructor

Try

#region " Constructors "
private EventSchoolsAndGradesSession()
{
    schoolgrade = new List<SchoolGrade>();
    schoolgrade.Add(new SchoolGrade("0", "0"));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top