May 1, 2009

How to access Page's session variable or create a new session variable in a normal C# class

This is Quite simple,

1 . We have lot of classes in the web application where the have the need to maintain or access the page's data or the server controls data between classes.
2. And there may be a situation where we need to send the data to the UI Page from the AppCode class or any class. For eg: i have processed something and need to send the data to the textbox in the UI Page.

This would be achieved by using

And like this you can create a session variable in a non UI class and access it in the page's class.

HttpContext.Current.Session["test1"] = "Got from test";

and the same way you can access the page's session variable in the non UI class like

string test = string.Empty;
test = HttpContext.Current.Session["test1"].ToString();

Thus we can maintain the data between the classes no matter whether it is UI or normal class.

No comments: