如何在会话变量中保存多个值

本文关键字:保存 变量 会话 | 更新日期: 2023-09-27 18:19:27

在我的项目中,我想存储最近访问的Id(如CompanyId),并根据Id在aspx网页上显示最近的5条记录。为此,我在会话类中使用了如下会话变量:

public static string RecentAssetList
{
    get
    {
        return HttpContext.Current.Session["RECENT_ASSET_LIST"].ToString();
    }
    set
    {
        HttpContext.Current.Session["RECENT_ASSET_LIST"] = value;
    }
}

从我的页面将值存储到会话中,如下所示。

    string assetList = "";            
    assetList += assetId.ToString() + ",";
    SessionData.RecentAssetList = assetList;

但如果新记录访问了仅显示新Id的会话,则它每次只存储一个Id。如何在会话中存储多个值,这些值是我想要从数据库中获取数据并显示在网格中的值。

如何在会话变量中保存多个值

您应该首先读取之前存储的值:

string assetList = SessionData.RecentAssetList;            
assetList += assetId.ToString() + ",";
SessionData.RecentAssetList = assetList;

但这种解决方案并不完美,因为新的ID将永远被附加。更好的解析和解释第一:

string assetList = SessionData.RecentAssetList;            
var ids = assetList.Split(',').ToList().Take(10).ToList();
ids.Add(assetId);
ids = ids.Distinct().ToList();
assetList = string.Join(",", ids);
SessionData.RecentAssetList = assetList;

我不确定我是否完全理解,但您可以在会话中存储一个字典:

public static Dictionary<int, int[]> RecentAssetLists
{
    get
    {
        var session = HttpContext.Current.Session;
        var dict = session["RECENT_ASSET_LISTS"];
        if (dict == null)
        {
            dict = new Dictionary<int, int[]>();
            session["RECENT_ASSET_LISTS"] = dict; 
        }
        return dict;
    }
}

或者,您可以定义自己的自定义对象并将其存储在会话中:

[Serializable]
public sealed class RecentAssetList
{
    private List<int> assets = new List<int>();
    public List<int> RecentAssets 
    {
        get { return this.assets; }
    }
}
public static RecentAssetList RecentAssetList
{
    get
    {
        var session = HttpContext.Current.Session;
        var assetlist = session["RECENT_ASSET_LIST"];
        return (RecentAssetList)assetlist;
    }
}

最简单的答案是(你仍然需要应用逻辑来只取最后5个,请参阅我的第二个例子,它已经应用了逻辑:

string assetList = SessionData.RecentAssetList;             
assetList += assetId.ToString() + ",";     
SessionData.RecentAssetList = assetList; 

因此,在添加值之前,您将检索已添加到会话中的值。

您还可以将RecentAssetList更改为List<string>,这样您就不必手动附加它,而只需添加到列表中。

public static List<string> RecentAssetList   
{   
    get   
    {   
        if (HttpContext.Current.Session["RECENT_ASSET_LIST"] == null)
            HttpContext.Current.Session["RECENT_ASSET_LIST"] = new List<string>();
        return HttpContext.Current.Session["RECENT_ASSET_LIST"].ToString();   
    }   
    set   
    {   
        HttpContext.Current.Session["RECENT_ASSET_LIST"] = value;   
    }   
}   

然后添加:

List<string> assetList = SessionData.RecentAssetList;             
assetList.Insert(0, assetId.ToString());     
SessionData.RecentAssetList = assetList.Take(5); // otherwise it's not changed in the session, you can write an extension method where you can add it to the list and submit that list to the session at the same time

.Take(5);是这样的,直到最后5个值插入