如何在会话变量中保存多个值
在我的项目中,我想要存储最近访问的 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。 如何根据我想要从数据库获取数据并显示在网格中的值在会话中存储多个值。
In my project i want store recently accessed Id's(like CompanyId) and based on Id's i need to display most recent 5 records on aspx webpage.For this i am using a session variable like below in my session class:
public static string RecentAssetList
{
get
{
return HttpContext.Current.Session["RECENT_ASSET_LIST"].ToString();
}
set
{
HttpContext.Current.Session["RECENT_ASSET_LIST"] = value;
}
}
And from my page storing the values into session like below.
string assetList = "";
assetList += assetId.ToString() + ",";
SessionData.RecentAssetList = assetList;
but it stores only one Id every time,if new record accessed session showing new one only.
How can i store multiple values in my session based that values i want to get data from Database and display in my grid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该首先读取之前存储的值:
但是这个解决方案并不完美,因为新的 ID 将永远附加。首先更好地解析和解释:
You should read the previously stored value first:
But this solution isn't perfect because new IDs will be appended forever. Better parse and interpret first:
我不确定我完全理解,但是您可以在会话中存储字典:
或者您可以定义自己的自定义对象并将其存储在会话中:
I'm not sure I fully understand, but you can store a dictionary in the session:
Or you can define your own custom object and store that in the session:
最简单的答案是(您仍然需要应用逻辑来仅获取最后 5 个,请参阅我的第二个示例,其中它已经应用了逻辑:
因此在添加值之前,您检索已添加到会话中的值。
您还可以更改RecentAssetList成为
List
,这样您就不必手动追加它,而只需添加到列表中,然后添加:
.Take(5);
。 > 是这样你只需要直到最后插入的 5 个值easiest answer would be (you will still have to apply the logic to only take the last 5, see my second example where it already applies the logic:
so before adding a value you retrieve the values already added to session.
You can also change RecentAssetList to be a
List<string>
so that you don't have to manually append it, instead just adding to the list.And then to add:
.Take(5);
is so that you only take up until the last 5 values inserted