我有一本字典,
如下所示Dictionary<Tuple<int, int>, bool> sampleDict= new Dictionary<Tuple<int, int>, bool>();
我在会话中添加的
if (!IsPostBack)
{
HttpContext.Current.Session.Add("SessionsampleDict", sampleDict);
}
现在我需要将值添加到字典中,所以我的代码就像这样。
sampleDict.Add(DictKey, true);
NOw 问题是当我使用回发返回我的页面时,我丢失了 sampleDict
中的所有数据。
我在这里做错了什么?如何在会话中添加字典的值?
sampleDict
将不会在会话中,只有其值会复制到会话中。修改会话变量后,您需要将值重新分配给会话变量。或者你可以这样尝试:
((Dictionary<Tuple<int, int>, bool>)HttpContext.Current.Session["SessionsampleDict"]).Add(DictKey, true);
试试这个:
Dictionary<Tuple<int, int>, bool> _sessionDict;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack || !(Session["SessionsampleDict"] is Dictionary<Tuple<int, int>, bool>))
{
Dictionary<Tuple<int, int>, bool> localDict = new Dictionary<Tuple<int, int>, bool>();
Session["SessionsampleDict"] = localDict;
}
_sessionDict = (Dictionary<Tuple<int, int>, bool>)Session["SessionsampleDict"];
}
现在,您可以使用页面中其他地方的本地引用_sessionDict
访问词典。
我猜当你将sampleDict添加到你的会话时,你正在制作它的副本并存储它,所以当你调用
sampleDict.Add(...)
它不会更新会话中的会话。
您可能必须在每次更新会话时更新会话中的一个,或者找到一种方法来仅操作会话中的一个。
sampleDict.Add(...);
HttpContext.Current.Session["SessionsampleDict"] = sampleDict;
类似的东西?
不太熟悉会话类,但我做了一个粗略的猜测。让我知道它是怎么回事:)
当您在会话中保存字典然后修改字典时,会话对象将不会更新,因为它不再是同一个对象。会话可以存储在数据库、Redis 或其他存储中,因此它只能克隆到原始对象。