views:

542

answers:

6

How can you make the ASP.net Session Data available to a JavaScript method? I found this link when I googled. Anyone has a better trick that does not use the ScriptManager?

+1  A: 

You have to put it into the page somehow. Using hidden form fields is one approach. Using webmethods like your link is a more sophisticated approach which gives you some ajax-powers.

If you don't actually need this value to update from the server except on post-back, you can just use the hidden input control HtmlInputHidden.

Michael Haren
A: 

A regular AJAX call to a ASHX that implements IRequiresSessionState

Why on earth would you want to though?

StingyJack
You wont wana know :( If only people would listen to me.
Perpetualcoder
I have had to do it too, Then I blew up the server to prove it was a bad idea. They got the picture =).
StingyJack
A: 

Honestly, the ScriptManager method looks pretty easy. Rolling your own solution would require an HttpHandler on the server side and an Ajax call, which doesn't seem worth the trouble in this case.

Adam Lassek
+2  A: 

The purpose of session is to hide details from the client. Sounds to me like you should convert it over to using cookies which is obviously trivial to retrieve via javascript.

Chris Lively
A: 

There are two alternatives I can see:

  1. Generate a JSON object of the Session data you want the JavaScript to have access to. Send this to the browser either during the initial page generation or as a result of a JSON Callback.
  2. Create an ASPX page you can call via AJAX which would return the value of a session variable with a given key.

#2 is probably what the ScripManager code is wrapping around, and you should probably just use that anyway. But I would be careful about deciding what session data you want to go to the client, and I'd use a Whitelist to only return the Session data I actually need to go down to the client.

foxxtrot
An ASHX Httphandler would be better than a full-blown ASPX page.
Adam Lassek
+3  A: 

If ditching the ScriptManager is your aim, exposing the page method is still a good option, just use javascript that doesn't rely on the ScriptManager js libraries.

I like the solution proposed in the linked page, but it might be a too wide open though. Maybe you want to create a strongly typed and controlled PageMethod for any/all Session items that you want to allow access to. That way you can't access some secret Session value accidentally.

Also, I think you need to tag the PageMethod with

VB

WebMethod(EnableSession:=True)

C#

WebMethod(true)

as I don't think EnableSession is on by default.

slolife
slolife, You just saved me a ton of work. You have no idea how much I was relying on session data for my app and I wanted to convert it to a more of an ajax app! Thank you so much!!! I wish I can vote you up more!.P.S. Its [WebMethod(EnableSession=true)] for C#
Scott