How to Get Session value in JavaScript from Asp.Net C# VB.Net

In server side we use the Session item container a lot. But some times we need to retrieve the Session variable value from client side like Javascript. Here in this small post I will show you how one can retrieve server side Session variable value or data from client side like Javascript. I did not use client side callback by using AJAX. I will show a very simple way to retrieve. Hope it will help you.

A simple Output:
How to Get Session value in JavaScript from Asp.Net Csharp VB.Net

Add a Label First:

<asp:Label ID="lblUser" runat="server" Text=""></asp:Label>

Declare a Session Variable from Server Side:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["UserName"] = "Shawpnendu";
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Session("UserName") = "Shawpnendu"
        End If
    End Sub

Now use Javascript Code to retrieve Session Variable:
C# Code:

<script type="text/javascript">
    document.getElementById("<%=lblUser.ClientID%>").innerText = 'Current Session User: ' + '<%= Session["UserName"] %>';
</script>

VB.Net Code:

<script type="text/javascript">
    document.getElementById("<%=lblUser.ClientID%>").innerText = 'Current Session User: ' + '<%= Session("UserName") %>';
</script>

Note: For this example write the Javascript code after adding the above Label.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code