Get or Set ASP.NET Session in Javascript.

Is there any possible method to directly set ASP.NET session variable with JavaScript? NO. You cannot directly set a session variable via JavaScript. But there is a work around.

In this article, I am going write examples to access and set Session variable Value in JavaScript and how to Set Session variable value from JavaScript in ASP.NET using PageMethods, XMLHttpRequest and JQuery Ajax call.

Set Session value in JavaScript using PageMethods

You can get and set session variable value from JavaScript in ASP.NET using Ajax ScriptManager‘sPageMethods. To use this you need to add ScriptManger tag in your page and enable propertyEnablePageMethods=”True”.

Check the below example to set and get session value in JavaScript using PageMethods.

Default.aspx.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protectedvoidPage_Load(objectsender, EventArgs e)
    {
    }
    [System.Web.Services.WebMethod]
    publicstaticvoidSetSessionValue(stringkey,stringvalue)
    {
        HttpContext.Current.Session[key] = value;
    }
    [System.Web.Services.WebMethod]
    publicstaticstringGetSessionValue(stringkey)
    {
        if(HttpContext.Current.Session[key] != null)
        {
            returnHttpContext.Current.Session[key].ToString();
        }
        else
        {
            return"Session value not found";
        }
    }

Default.aspx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<headid="Head1"runat="server">
    <title>Set Session Value from JavaScript in ASP.NET using PageMethodstitle>
    // <![CDATA[
        functionSetUserName() {
            varuserName = document.getElementById("tbUserName").value;
            PageMethods.SetSessionValue('UserName', userName, null, null);
        }
        functionGetUserName() {
            PageMethods.GetSessionValue('UserName', OnSuccess, OnFailure);
        }
        functionOnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        functionOnFailure(error) {
            alert(error);
        }
  
    
// ]]>
head>
<body>
    <formid="form1"runat="server">
    <asp:ScriptManagerID="scripman1"runat="server"EnablePageMethods="True">
    asp:ScriptManager>
    <div>
        Enter an user name,
        <inputid="tbUserName"type="text"/>
<inputtype="button"value="Set User Name"onclick="SetUserName()"/>
        <inputtype="button"value="Show UserName"onclick="GetUserName()"/>
    <labelid="lbUserName">This is a username from session variablelabel>
    div>
    form>
body>
html>

Set Session value in JavaScript using XMLHttpRequest in ASP.NET

You can set and get server side session variable value from JavaScript in ASP.NET using usingXMLHttpRequest. The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can access Server Side value from JavaScript client side by using this object without refreshing or reloading the page.

Check the below example to get and set session value in JavaScript in ASP.NET using XMLHttpRequest.

Default.aspx.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
protectedvoidPage_Load(objectsender, EventArgs e)
    {
        if(Request.QueryString["Method"] == "SetUserName")
        {
            SetUserName(Request.QueryString["Value"].ToString());
        }
        elseif(Request.QueryString["Method"] == "GetUserName")
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            GetUserName();
        }
    }
    privatevoidSetUserName(stringuserName)
    {
        Session["UserName"] = userName;
    }
    privatevoidGetUserName()
    {
        Response.Clear();
        if(Session["UserName"] != null)
        {
            Response.Write(Session["UserName"].ToString());
        }
        else
        {
            Response.Write("Session Value not found");
        }
        Response.End();
    }

Default.aspx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<headid="Head1"runat="server">
    <title>Set Session variable value in JavaScript using XMLHttpRequesttitle>
    // <![CDATA[
        functionSetUserName() {
            varuserName = document.getElementById("tbUserName").value;           
            varxmlhttp;
            if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = newXMLHttpRequest();
            }
            else{// code for IE6, IE5
                xmlhttp = newActiveXObject("Microsoft.XMLHTTP");
            }
            varurl = "WebForm1.aspx?Method=SetUserName&Value="+ userName;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);                    
        }
        functionGetUserName() {
            varxmlhttp;
            if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = newXMLHttpRequest();
            }
            else{// code for IE6, IE5
                xmlhttp = newActiveXObject("Microsoft.XMLHTTP");
            }
            varurl = "WebForm1.aspx?Method=GetUserName";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("lbUserName").innerHTML = xmlhttp.responseText;
        }
 
    
// ]]>
     
head>
<body>
    <formid="form1"runat="server">
    <div>
    Enter an user name,
        <inputid="tbUserName"type="text"/>
<inputtype="button"value="Set User Name"onclick="SetUserName()"/>
        <inputtype="button"value="Show UserName"onclick="GetUserName()"/>
    <labelid="lbUserName">This is a username from session variablelabel>
    div>
    form>
body>
html>

Get and Set Session value in JavaScript using JQuery ajax call

You can access or set session variable value from JavaScript in ASP.NET using using JQuery ajax method.

Check the below example to set session variable value in JavaScript using JQuery ajax call.
Note: You need add reference for JQuery script file to use JQuery ajax method.

Default.aspx.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protectedvoidPage_Load(objectsender, EventArgs e)
    {
    }
    [System.Web.Services.WebMethod]
    publicstaticvoidSetSessionValue(stringkey, stringvalue)
    {
        HttpContext.Current.Session[key] = value;
    }
    [System.Web.Services.WebMethod]
    publicstaticstringGetSessionValue(stringkey)
    {
        if(HttpContext.Current.Session[key] != null)
        {
            returnHttpContext.Current.Session[key].ToString();
        }
        else
        {
            return"Session value not found";
        }
    }

Default.aspx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<headid="Head1"runat="server">
    <title>Set Session value from JavaScript in ASP.NET using JQuery ajaxtitle>
    <scripttype="text/javascript"
    
    // <![CDATA[
        functionSetUserName() {
            varuserName = document.getElementById("tbUserName").value;
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/SetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName","value":"'+ userName + '"}',
                success: function(result) {
                    //Session value saved successfully
                },
                error: function(xhr, status, error) {
                    //Failed to save Session value
                }
            });
        }
        functionGetUserName() {
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/GetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName"}',
                success: function(result) {
                    OnSuccess(result.d);
                },
                error: function(xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        functionOnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        functionOnFailure(error) {
            alert(error);
        }
  
    
// ]]>
head>
<body>
    <formid="form1"runat="server">
    <div>
        Enter an user name,
        <inputid="tbUserName"type="text"/>
<inputtype="button"value="Set User Name"onclick="SetUserName()"/>
        <inputtype="button"value="Show UserName"onclick="GetUserName()"/>
    <labelid="lbUserName">This is a username from session variablelabel>
    div>
    form>
body>
html>
From external JS file.
This is in Test.js file.
$(document).ready(function () {
$(‘#btnTEST’).click(function (e) {
e.preventDefault();
debugger;
//var jsonText = JSON.stringify({ EmpName: “NENU” });$.ajax({

type: “POST”,

url: “SetSession.aspx/GetSetSessionValue”,

data: ‘{ EmpName: “SRI”}’,

contentType: “application/json; charset=utf-8”,

dataType: “json”,
async: false

});
});
});

Code behind page:

[System.Web.Services.WebMethod]

public static void GetSetSessionValue(string EmpName)
{

//As this is a static method, we can access session using HttpContext.Current.Session

if (EmpName.Length > 0)
{

HttpContext.Current.Session[“EmpName”] = EmpName;

}

if (HttpContext.Current.Session[“EmpName”] != null)
{

EmpName = Convert.ToString(HttpContext.Current.Session[“EmpName”]);

}

}

If you are facing any issues while calling Weebmethod

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

(Or just comment the line)

Also if friendly URLs are enabled you need to change

url: "ConsultaPedidos.aspx/GetClients",

To:

url: '<%= ResolveUrl("ConsultaPedidos.aspx/GetClients") %>',

Hope this help somebody else

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s