Wednesday, May 26, 2010

jQuery and session

How to get Session value in jquery method? - Stack Overflow
In this Stack Overflow discussion there is an example on how to communicate from client-side JavaScript (jQuery) and server-side code. The application of this is to exchange values from ASP.NET session, which are not directly available to JavaScript.
This is a neat way to store and retrieve values in the Session if you don't mind the extra traffic.

Effectively, this is what you do...
Server side:
using System.Web.Services;
public static string GetSession()
return Session["CoBrowse"].ToString();
then call this method client side using jQuery:
type: "POST",
url: "./Default.aspx/GetSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', result.d);

Or, alternatively, you could use the simpler jQuery call:

$.post(url, data, callback, type)


Unfortunately, the approach above does not really work in my environment. After reading about a few more cases I'm inclined to put my faith in cookies. That solution seems to work better as a media for client-server information exchange.
When using cookies, however, pay attention on the Path value. If you are redirecting from one page to another, you have to use '/' as the cookie path.

$.cookie('MyPhoto_SelectedTab', 'yo, mate', { path: '/' } );
top.location = 'http://' + + '/MyPhotos/photos.aspx';

No comments: