How to access Session variables and set them in javascript?

In code-behind I set Session with some data.

Session["usedData"] = "sample data";

And the question is how can I get the Session value(in my example; "sample data") in javascript and set Session["usedData"] with a new value?


Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById


Javascript can not directly set session values. For setting session values from javascript I do ajax call as follows.

Check Online

At ASPx file or html,

 <script type="text/javascript">
 $(function(){
   //Getting values from session and saving in javascript variable.
   // But this will be executed only at document.ready.
   var firstName = '<%= Session["FirstName"] ?? "" %>';
   var lastName = '<%= Session["LastName"] ?? "" %>';

   $("#FirstName").val(firstName);
   $("#LastName").val(lastName);

   $('Button').click(function(){
     //Posting values to save in session
     $.post(document.URL+'?mode=ajax', 
     {'FirstName':$("#FirstName").val(),
     'LastName':$("#LastName").val()
     } );
   });

 });

At Server side,

protected void Page_Load(object sender, EventArgs e)
 {
      if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax")
      {
        //Saving the variables in session. Variables are posted by ajax.
        Session["FirstName"] = Request.Form["FirstName"] ?? "";
        Session["LastName"] = Request.Form["LastName"] ?? "";
      }
 }

For getting session values, as said by Shekhar and Rajeev

var firstName = '<%= Session["FirstName"] ?? "" %>';

Hope this helps.


Try This

var sessionValue = '<%=Session["usedData"]%>'

Assuming you mean "client side JavaScript" - then you can't, at least not directly.

The session data is stored on the server, so client side code can't see it without communicating with the server.

To access it you must make an HTTP request and have a server side program modify / read & return the data.