I have got below code to GET dictionary type of session variable value. Please see the below code
In my code, I just use below code to get any value from my session variable:
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))
{
valu开发者_JAVA技巧e = form[key];
}
}
}
}
catch (Exception ex)
{
Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary");
}
return value;
}
}
Now I want to write a method to SET the value for particular session key, for example
SessionDictionary.SetValue("FORMDATA", "panelOpen") = "First";
Now if I again go for below code it should give me "First" for my panelOpen key.
string panelOpen = SessionDictionary.GetValue("FORMDATA", "panelOpen");
Please suggest!
The "SetValue" would be almost identical, except for the line value = form[key];
. That should become form[key] = value;
.
No need to "set the dictionary back into the session" as the reference to that same dictionary is still present in the session.
Examples:
Setting a 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");
}
}
}
Removing a value:
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");
}
}
}
精彩评论