3

似たような見出しのトピックがあることは知っていますが、これはちょっと違います。

まず、1 つのセッションに複数の値を格納するには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

4 に答える 4

4

ここに落とし穴があります。

あなたのコードは問題ありません。リストを元に戻す必要はありません (それほど面倒なことではありません)。

ただし、これを 1 つのサーバー ( ) で実行する場合に限ります <sessionstate mode="inproc" />

これを複数のサーバーにスケールアップすると、List<>としてマークされていない問題が発生し[Serializable]ます。あなたのソリューションは直接機能しません。

簡単な修正は、次を使用することです。

[Serializable]
class MyList : List<int>
{
}
于 2013-08-26T08:40:57.547 に答える
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"]) : "";
            }
于 2013-08-26T08:39:52.857 に答える
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);


    }
于 2013-08-26T08:23:13.063 に答える