Reputation: 7707
I am using C#.
I have got below format values in my SESSION variable ["FROMDATA"], I am using DICTIONARY to store the FORM Posted Data. Please see the related question.
Below are the some values in my SESSION Variable.
1) key - "skywardsNumber" value-"99999039t"
2) key - "password" value-"a2222222"
3) key - "ctl00$MainContent$ctl22$FlightSchedules1$ddlDepartureAirport-suggest" value-"London"
4) key - "ctl00$MainContent$ctl22$ctl07$txtPromoCode" value-"AEEGIT9"
.
.
....so on
Now I want to create a CLASS with METHOD in it, in which I will just pass the "KEY" and it will first check it for NULL OR EMPTY and then it will return its value from the SESSION Variable ["FROMDATA"].
Please suggest using C#.
Upvotes: 0
Views: 12710
Reputation: 94645
Try this,
public class Test
{
public static string GetValue(string key)
{
string value = string.Empty;
if (HttpContext.Current.Session["FROMDATA"] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session["FROMDATA"];
if(form.ContainsKey(key))
value = form[key];
}
return value;
}
}
EDIT:
public static string GetValue(string sessionkey,string key)
{
string value = string.Empty;
if (HttpContext.Current.Session[sessionkey] != null)
{
Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[sessionkey];
if(form.ContainsKey(key))
value = form[key];
}
return value;
}
Upvotes: 5
Reputation: 7691
Try this: you'll have to tweak it a bit for it to complie. But you'll get the basic idea
public class Session
{
private const string _skyWardsNumber = "skyWardsNumber";
// Add other keys here
public string SkyWardsNumber
{
get
{
object str = (ReadFromDictionary(_skyWardsNumber);
if (str != null)
{
return (string) str;
}
else
{
return string.Empty;
}
}
set
{
WriteToDictionary(_skyWardsNumber, value);
}
}
public object ReadFromDictionary(string key)
{
IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
if (dictionary != null && dictionary.ContainsKey(key))
{
return dictionary[key];
}
else
{
return null;
}
}
public object WriteFromDictionary(string key, object value)
{
IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
if(dictionary == null)
WriteToContext("Dictionary", new Dictionary<string, string>())
dictionary = (ReadFromContext("Dictionary") as IDictionary);
if (dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(//add new keyvaluepair.);
}
}
private static void WriteToContext(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
private static object ReadFromContext(string key)
{
if(HttpContext.Current.Session[key] != null)
return HttpContext.Current.Session[key] as object;
return null;
}
}
Upvotes: 0