views:

825

answers:

3

Is there a way to modify the current Session() variable using jQuery? If it involves deconstructing the ViewState then I'm not really interested. Just curious if there was some easy way to do it.

Thanks!

A: 

Session is stored on the server and you can't access it from jQuery unless you make an ajax call and get the session details from server.

Other than the fact that both ViewState and Session helps developer maintain state in their web application, they have nothing to do with each other.

EDIT:

If you want to modify the session using Ajax. Create an HTTP handler SessionHelper.ashx. This session handler can take 'SessionVariableName' and 'SessionVariableValue' as Query String parameters and modify the session state on the server. You can call this handler from jQuery using $.ajax method.

Please keep in mind that if you expose an handler like that, you will have to protect it against misuse as any person can call the handler directly and modify the Session variables. [e.g. If you store User role/privileges in session, a hacker can modify this role/privileges through this handler.]

SolutionYogi
hm.. ok, how would i do that?
Jason
+2  A: 

If you need to pass a per session property between jQuery and the server you could try using cookies instead.

Otherwise you'll have to create a custom handler (ashx) file or a WebMethod or similar that lets you access it with Ajax calls.

Keith
+1  A: 

jQuery


$.get("http://somewhere/page.aspx",
      {sessionVar: "something"},
      function(data)
      {
          alert("Session(\"something\") = " + data);
      }
);

page.aspx:


Response.Write(Session[Request.QueryString["sessionVar"]]);

That's with no error checking or anything...

mgroves
Good example (+1) but I would add that you need to be careful of security - this would make any session property externally visible, but you would probably want to restrict what could be accessed.
Keith
Absolutely correct. What I have above is a very minimal, poor example, just for illustration.
mgroves