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?
6 Answers
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.
1 Comment
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.
Comments
A regular AJAX call to a ASHX that implements IRequiresSessionState
Why on earth would you want to though?
2 Comments
There are two alternatives I can see:
- 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.
- 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.