在单个会话中存储和检索多个值

时间:2013-08-26 07:59:46

标签: c# asp.net list session

我知道有类似标题的主题,但这有点不同。

首先,为了在单个会话中存储多个值,我必须使用List,而我将列表中的值存储在会话中,对吧?

如果是这样,当我想向List中添加一个已经在会话中的值时,我会从会话中检索List并添加该值。但是,每次添加/删除List中的值时,是否需要将列表分配回会话?或者,默认情况下,当我操作它时会在会话中自动更新它,因为它是在会话中首先分配的,之后是。

更新:提供我的问题的示例代码

public void assignNewID(int currentID)
{
    if(Session["usersID"] == null)
    {
        Session["usersID"] = new List<int>();
    }

    if(currentID != null)
    {
        var list = (List<int>)Session["usersID"];
        list.Add(currentID);

        // now should I hereby assign the list back to
        // the session like:
        // Session["usersID"] = list;
        // or it gets automatically updated in the session by default ?
    }
}

4 个答案:

答案 0 :(得分:7)

List是一种引用类型,因此您将reference存储到会话中,如果对象更新,将会更新

Session gets updated for reference type

答案 1 :(得分:4)

这里有一个问题。

您的代码没问题,无需重新分配列表(不是那样会有很多麻烦)。

但只要你在1服务器(<sessionstate mode="inproc" />)上运行它。

如果您将其扩展到多个服务器,则会遇到List<>未标记为[Serializable]的问题。您的解决方案不会直接起作用。

一个简短的解决方法是使用:

[Serializable]
class MyList : List<int>
{
}

答案 2 :(得分:2)

试试这个:

// Saving in session
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht.Add("EmployeeName", "EmpName Value");
            ht.Add("Designation", "Designation Value");
            ht.Add("Department", "Department Value");
            Session["EmployeeInfo"] = ht;
            //Retrieve from session
            if (Session["EmployeeInfo"] != null)
            {
                string strEmployeeName = ht.ContainsKey("EmployeeName") ? Convert.ToString(ht["EmployeeName"]) : "";
                string strDesignation = ht.ContainsKey("Designation") ? Convert.ToString(ht["Designation"]) : "";
                string strDepartment = ht.ContainsKey("Department") ? Convert.ToString(ht["Department"]) : "";
            }

答案 3 :(得分:0)

参见此示例

public static class SessionManager
{
    public static List<Entity.Permission> GetUserPermission
    {
        get
        {
            if (HttpContext.Current.Session["GetUserPermission"] == null)
            {
                //if session is null than set it to default value
                //here i set it 
                List<Entity.Permission> lstPermission = new List<Entity.Permission>();
                HttpContext.Current.Session["GetUserPermission"] = lstPermission;
            }
            return (List<Entity.Permission>)HttpContext.Current.Session["GetUserPermission"];
        }
        set
        {
            HttpContext.Current.Session["GetUserPermission"] = value;
        }
    }
 }

现在无论如何

    protected void chkStudentStatus_CheckedChanged(object sender, EventArgs e)
    {
        Entity.Permission objPermission=new Entity.Permission();
        SessionManager.GetUserPermission.Add(objPermission);
        SessionManager.GetUserPermission.RemoveAt(0);


    }
相关问题