Tuesday, June 12, 2012

How to get Session value using javascript?


In some of the cases we want to access Session variable value in Client side. but getting session value in client side is bit difficult, because is it server side object which can not be accessed in client side. But even then we can make trick to access Session object value in client side. Here I am explaining easy way to for-

How to get Session value using JavaScript?

To complete this task I have used HiddenField. In this example I have assigned Session object value to HiddenField variable which can be easily accessed from client side.

Here is code-

.aspx code-

 
<head runat="server">
    <title>How to get session value in javascript</title>
    <script type="text/javascript">
        function GetSessionValue() {
            var hdnSession= document.getElementById("<%= hdnSession.ClientID %>");
            alert(hdnSession.value);
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnGetSession" runat="server" OnClientClick ="return GetSessionValue();" Text="Get Session Value" />
        <asp:HiddenField ID="hdnSession" runat="server" />
    </div>
    </form>
</body>


I above code I have taken one HiddenField Varible, using this HiddenField I will get value of Session variable. To get value of HiddenField I have defined one client side function called- GetValue(). 

.cs code-

Now I have set Session variable value in Page_Load() event-
  

 protected void Page_Load(object sender, EventArgs e)
    {
      //Setting data to Session variable
        Session["Data"]="Jitendra" ;

      //Copying Session data HiddenField variable
        hdnSession.Value = Session["Data"].ToString();
    }

In above code, I have copied some data to Session variable, in next line same data I have copied to HiddenFiled variable, so that I can access this HiddenFiled value from client side.  

Now done, when you will click on button you will get output like this-


Getting Session value using JavaScript.

Thanks


No comments:

Post a Comment