How to get/set the value of a session variable using javascript/jQuery?

You wanna set the session value using javascript/jQuery. Or you would like to get the session value in javascript/jQuery.

There is a little problem here.

Javascript, used for manipulation of web documents, works only at browser end – as it resides at client Side. But Session is a server side state management technique whose context is restricted to the server side.

So, we are left with two options here

  1. You can access the Session variable by firing Ajax request from client to the server
  2. Send the session value from server to client side (E.g., using HiddenField). Javascript can use or update this value. This value would be posted back to the server during form submission or postback.

 

Below picture explains the problem and the available options

 

Session

 

 

  1. Using Ajax:

You can fire an Ajax request from client side (browser) to the server to get the session value. You can use this same technique for setting the session value as well. I have written an article on how to use Ajax in ASP.Net Web Form Application here.

Session Ajax Form

 

Below GetSetSessionValue method is used for both setting and getting the session value. When you click “Get session value” button, the session value is got and placed in textbox. You can even enter the value and click “Set Session value” to set the session value. As this is a static method, we are using HttpContext.Current.Session to handle session values.


[System.Web.Services.WebMethod]

public static string 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"]);

    }

 return EmpName; // Return the session value

}

Below callAjaxMethod will call the server side method using Ajax. We need to pass the Aspx file name and method name details to jQuery Ajax function.We are setting the session value to textbox on successful completion of Ajax request.


<script type="text/javascript">

function callAjaxMethod(e) {

//To prevent postback from happening as we are using ASP.Net TextBox control

//If we had used input html element, there is no need to use ' e.preventDefault()' as posback will not happen

e.preventDefault();

$.ajax({

type: "POST",

url: "WebForm1.aspx/GetSetSessionValue",

data: '{ EmpName: "' + $("#<%=txtSessionValue.ClientID%>").val() + '" }',

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

dataType: "json",

success: function (response) {

$('#<%=txtSessionValue.ClientID%>').val(response.d);

},

failure: function (response) {

$('#<%=txtSessionValue.ClientID%>').val("Error in calling Ajax:" + response.d);

}

});

}

</script>

 

Aspx Page Markup:


<table>

<tr>

<td>Session Value of "EmpName":</td>

<td><asp:TextBox ID="txtSessionValue" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td>

<asp:Button ID="btnGetSessionValue" runat="server" OnClientClick="callAjaxMethod(event)" Text="Get Session Value" />

</td>

<td>

<asp:Button ID="btnSetSessionValue" runat="server" OnClientClick="callAjaxMethod(event)" Text="Set Session Value" />

</td>

</tr>

</table>

 

2. Using HiddenField:

You can use any server side ASP.Net control to send data from server to client side. We are using HiddenField so that the data will not be visible to the user. Of course, users can view this data to viewing the source of the page. I have written an article on how to use HiddenFiled in javascript 

In PageLoad event method, we are setting the session value.


protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

//Set the session value first time

Session["EmpName"] = "Scott";

txtSessionValue.Text = Convert.ToString(Session["EmpName"]);

}

}

When the Page is submitted, we can get the HiddenField value.


protected void btnSubmit_Click(object sender, EventArgs e)

{

//Set the session value from HiddenField

Session["EmpName"] = hdnSession.Value;

txtSessionValue.Text = Convert.ToString(Session["EmpName"]);

}

In the below javascript click event, we are setting the textbox value to hiddenField Value


<script type="text/javascript">

$(document).ready(function () {

$('#<% =btnSubmit.ClientID %>').click(function (e) {

$('#<% =hdnSession.ClientID %>').attr('value', $('#<%= txtSessionValue.ClientID %>').val());

});

}

);

</script>

 

Aspx Page Markup:


<div>

Session Value : <asp:TextBox ID="txtSessionValue" runat="server"></asp:TextBox>

<asp:HiddenField ID="hdnSession" runat="server" Value=""  />

<asp:Button ID="btnSubmit" runat="server" Text="Set Session Value" OnClick="btnSubmit_Click" />

</div>

Summary:

Javascript resides at client side whereas Session is a server side state management technique resides at server side.

So we can think of two options

  1. From Client Side, query the value on server using Ajax
  2. While sending the page from server to client, send this data. Update this data at client, if needed. Get this data when postback happens or when page is submitted.

We have discussed both of the options in detail above.

Thanks for reading the article. If you like this article, Please subscribe in the below form.


Posted

in

, ,

by

Tags: