How To Use Session Value Client Side Using JavaScript In ASP.NET

Introduction

In this article, I am going to explain how to use the value of the session variable at client-side using JavaScript in ASP.NET with an example.

Implementation

By using Session property, you can easily access the values of the session in JavaScript or jQuery based on our requirement. So, let's take one example for demonstration.

We will write JavaScript code, shown as below.
  1. <script type="text/javascript">  
  2.     $(function () {  
  3.         var name = 'Welcome ' + ' <%=Session["UserName"] %>'  
  4.         $('#lblusr').text(name)  
  5.     });  
  6. </script>  

Now, let's understand how to integrate the created JavaScript in Aspx.

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3.     <title>How to use Session Value Client Side Using JavaScript in Asp.Net</title>  
  4.     <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>  
  5.     <script type="text/javascript">  
  6.         $(function () {  
  7.         var name = 'Welcome ' + ' <%= Session["UserName"] %>'  
  8.         $('#lblusr').text(name)  
  9.         });  
  10.     </script>  
  11. </head>  
  12. <body>  
  13.     <form id="form1" runat="server">  
  14.         <div>  
  15.             <label id="lblusr" />  
  16.         </div>  
  17.     </form>  
  18. </body>  
  19. </html>  

You can observe the above code. In this, we are trying to get " UserName" session value client-side using Session property in JavaScript.

Now, open the code behind file and write the code like, as shown following.

C#

  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         Session["UserName"] = "Nikunj_Satasiya";  
  4.     }  

VB.NET

  1. Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load  
  2.         Session("UserName") = " Nikunj_Satasiya "  
  3.     End Sub  
Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.