.net – How to access Session variables and set them in javascript?

.net – How to access Session variables and set them in javascript?

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 cant 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

.net – How to access Session variables and set them in javascript?

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.

Leave a Reply

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