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

时间:2012-01-05 13:57:04

标签: c# session-variables

在我的项目中,我想要商店最近访问的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。 如何根据我想从数据库中获取数据并在网格中显示的值在会话中存储多个值。

3 个答案:

答案 0 :(得分:2)

您应首先阅读先前存储的值:

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;

答案 1 :(得分:0)

最简单的答案是(你仍然需要应用逻辑只取最后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个值时才会占用

答案 2 :(得分:0)

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

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;
    }
}
相关问题