我有以下代码到GET字典类型的会话变量值。请参阅以下代码
在我的代码中,我只是使用下面的代码从我的会话变量中获取任何值:
string panelOpen = SessionDictionary.GetValue("FORMDATA", "panelOpen");
public class SessionDictionary
{
public static string GetValue(string dictionaryName, string key)
{
string value = string.Empty;
try
{
if (HttpContext.Current.Session[dictionaryName] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName];
if (form.ContainsKey(key))
{
if (!string.IsNullOrEmpty(key))
{
value = form[key];
}
}
}
}
catch (Exception ex)
{
Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary");
}
return value;
}
}
现在我想写一个方法来设置特定会话密钥的值,例如
SessionDictionary.SetValue("FORMDATA", "panelOpen") = "First";
现在如果我再次使用下面的代码,它应该为我的panelOpen键给我“First”。
string panelOpen = SessionDictionary.GetValue("FORMDATA", "panelOpen");
请建议!
答案 0 :(得分:2)
除了行value = form[key];
之外,“SetValue”几乎相同。那应该是form[key] = value;
。
无需“将字典设置回会话”,因为会话中仍然存在对该字典的引用。
示例:
设定值
public static void SetValue(string dictionaryName, string key, string value)
{
if (!String.IsNullOrEmpty(key))
{
try
{
if (HttpContext.Current.Session[dictionaryName] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName];
if (form.ContainsKey(key))
{
form[key] = value;
}
}
}
catch (Exception ex)
{
Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary");
}
}
}
删除值:
public static void RemoveValue(string dictionaryName, string key)
{
if (!String.IsNullOrEmpty(key))
{
try
{
if (HttpContext.Current.Session[dictionaryName] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName];
form.Remove(key); // no error if key didn't exist
}
}
catch (Exception ex)
{
Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary");
}
}
}