How to access Session in javascript


In this article we learn about how we can access ASP.NET server side session variable or data in client side JavaScript.
I have requirement for current user session variable in client side to perform some action based on user and its role.

Here are method or way to interact session variable in client side or in JavaScript.

1. Directly access session variable with mix code( Server side)
as per the below code.
     //First way to access session 
     console.log("UserId:" + '<%=Session["UserId"] %>');
     console.log("UserRole:" + '<%=Session["UserRole"] %>');
2. Fetch session value from HiddenField
To fetch session value from hidden field first we have to set session data in server side and then we can access stored hidden value data in client side javascript.
//Set session value to hidden field for access this value in jquery 
     protected void setSessionToHiddenValue()
         Session.Add("UserId", "Arvind");
         Session.Add("UserRole", "Admin");
         hdnUserId.Value = Convert.ToString(Session["UserId"]);
         hdnUserRole.Value = Convert.ToString(Session["UserRole"]);
     //We can access hidden session data as below 
     console.log("UserId:" + '<%= hdnUserId.Value %>');
     console.log("UserRole:" + '<%= hdnUserRole.Value %>');


In this article we have learn about accessing server side session variable in client side for take action based on current session. 

1 comment:

Dynamic Query in LINQ using Predicate Builder

Introduction This tutorial explain how to create dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query and Q...

Learn More