use session from class library

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have an asp.net page which uses a class from a class library. Is there any
way to store values into the session from code inside the classes in the
class library
 
Hi Scott,

You have two options here you can use the:

System.Web.SessionState.HttpSessionState object and then call stuff in
from that from within the class - I think you can set to it as well
from memory - you will probably have to inherit from Page though in
order to do it so the class understands what is going on at an ASP.NET
level with the server.

The only problem with this is that it makes your class dependent on the
state of the page which can be problematical and also a pain to debug.

If you were to take the hard "best practice" line then what you could
also do is expose some public variables from within your class and then
within the page you call the Variable Get and put the item in the
Session object from the page. This maintains the class object as
separate from the page object which should heighten re-use as well.

An example.

Test.cs

public class myTest{


string _text

/// <summary>Creates a new instance of mytest </summary>
public myTest(){
}

/// <summary>Creates a new instance of mytest with the string
set</summary>
public myTest(string val){
_text = val;
}

public string Text {
get {
return (_text);
}
}
}

//// end of test.cs

in your page test.aspx now put the lines.

myTest testobj = new myTest("some string");

Session["session_var"] = myTest.Text;

and then you'll have your sesison variable set to a value from the
class itself.

Ultimately I would personally go down this second approach as it will
make my code easier to maintain, simpler to read and understand what is
going on and probably more bug free - certainly easier to debug as you
can test the class and page independently...

This is all in C# so if anyone has a VB example that may help too..

Cheers
AndrewF
 
Hi Scott,

use :
HttpContext.Current.Session("test")

Let me know if you have any more questions..

Cheers,
Tom Pester
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top