Skip to content

Instantly share code, notes, and snippets.

@teocci
Last active June 4, 2016 04:09
Show Gist options
  • Save teocci/3cc57400d91c297791a0f0b0251fc401 to your computer and use it in GitHub Desktop.
Save teocci/3cc57400d91c297791a0f0b0251fc401 to your computer and use it in GitHub Desktop.

Accessing Session from Javascript using JQuery, AJAX in ASP.Net

Well, well well, this is one of those problems which crops out many a time while developing web application “How do i access session variables in my Javascript?” Usually the answer is you cannot, simply because sessions are stored on the server (backside) and your application is running on some remote client (Firefox de m...). Theoretically that is truth, but not the whole truth. Let us dispel the misconception.

Accessing session variables in ASP.Net

Well as we said before, it is not completely true when someone tells you, that session values cannot be used in JavaScript. It can be done, but with limitations. You can only have read-only access:).

This sample will show how we do it

//Consider you have set the following session variable in code-behind
//Session[“UserName”] = “kalpesh”
 
function PrintUserName(){
    var sv = '<%= Session["paramConTarjeta"] %>'
} 

//When you execute the aspx page; the value should be replaced by the session value
//e.g. var sv = ‘kalpesh’

Pretty simple isnt it? For most purposes this will do just fine. Where the value is largely static i.e. it doesn’t change much often we can just get by with no issues. What do you do for values which are constantly modified and need to be displayed to the user, without forcing the user to refresh the page?

Accessing session variables using AJAX

As the question states, we are in a soup when we need to display constantly modifying values. If we have to force the user to modify, you can very well guess what can happen?:)

Despite the popular belief it is quite easy to access session values using AJAX, if you know where to look😀 (I have been hunting for it for quite a while, before having a deja vu :))

All we need to do is create an asmx Web Service which exposes the desired method as shown below

//The important part is “EnableSession = true”
[WebMethod(EnableSession = true)]
public string GetSessionValue(String Name){
    string sessionVal = String.Empty;
    if (Session != null && Session[Name] != null){
        sessionVal = Session[Name].ToString();
    }
    return sessionVal;
}

Invoking web service methods using JQuery

Calling our web method from javascript is very easy. There are a whole lot of tutorials around so i wont get into details.

I have can implemented a generic method to due the AJAX calls offloading for me

var webMethod_result;
function WebMethod_OnError(result, response){
    //debugger
    //Dummy function for page method ajax call
}
function WebMethod_OnSuccess(result, response){
    //Dummy function for page method ajax call
    webMethod_result = result.d;
}
 
function CallWebMethod(MethodName, ObjParams, isAsync, OnSuccessHandler, OnErrorHandler){
    try{
        //Set the callback methods for success and error
        if (OnSuccessHandler == undefined || typeof (OnSuccessHandler) == 'undefined'){
            OnSuccessHandler = WebMethod_OnSuccess
        }
 
        if (OnErrorHandler == undefined || typeof (OnErrorHandler) == 'undefined'){
            OnErrorHandler = WebMethod_OnError
        }
 
        //Serialize the webmethod function parameters
        var serializedParams = '';
        //using Json2.js; 
 
        //you can download the file from the location mentioned in the references
        serializedParams = JSON.stringify(ObjParams); 
 
        //Make the ajax calls
        return $.ajax({
            type: 'POST',
            async: isAsync,
            url: 'TestJQueryWebservice.asmx/' + MethodName,
            data: serializedParams,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: OnSuccessHandler,
            error: OnErrorHandler
        });
    }
    catch (e)
    {
        //suppress error
    }
    return;
}

The next stop is to define proxy methods which can be called from our javascript function

//Proxy method for getting the Session value for a given name 
function GetSessionValue(SessionName, OnSuccessHandler, OnErrorHandler){
    //set web method parameters; should be same as parameter name else the web 
 
    //method wont be called
    var methodParams = new Object();
    methodParams.Name = SessionName; 
 
    CallWebMethod('GetSessionValue', methodParams, false, OnSuccessHandler, OnErrorHandler); 
 
    //get the response
    return webMethod_result;
}

And calling the method from javascript? Easy:)

var sessionVal;
sessionVal = GetSessionValue('TestJQuery');

Modifying session variables

Its pretty simple to add a method to modify the session variables. Well this is how you do it.

The web method

[WebMethod(EnableSession = true)]
public void SetSessionValue(String Name, String Value){
    string sessionVal = String.Empty;
 
    if (Session != null){
        Session[Name] = Value;
    }
}

The proxy method

function SetSessionValue(SessionName, SessionValue, OnSuccessHandler, OnErrorHandler){
    //set web method parameters; should be same as parameter name else the web method wont be called
    var methodParams = new Object();
 
    methodParams.Name = SessionName;
    methodParams.Value = SessionValue;
 
    CallWebMethod('SetSessionValue', methodParams, false, OnSuccessHandler, OnErrorHandler);
}

And the call from javascript

//update session value
SetSessionValue('TestJQuery', 'UpdatedValue');

Sweet. It can’t get better than this.

For those who believe in the paradigm of “seeing is believing”, I have setup a GitHub repository for the post. You can get it here: GitHub -JSSessionManager

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment