Access Session variables in JavaScript

75,851

Solution 1

You can do it this way for a String variable:

<script type="text/javascript">
    var someSessionVariable = '@Session["SomeSessionVariable"]';
</script>

Or like this if it's numeric:

<script type="text/javascript">
    var someSessionVariable = @Session["SomeSessionVariable"];
</script>

This is really not a very clean approach though, and requires inline JavaScript rather than using script files. Be careful not to get carried away with this.

Solution 2

I personally like the data attribute pattern.

In your Razor code:

<div id="myDiv" data-value="@Request.RequestContext.HttpContext.Session["someKey"]"></div>

In your javascript:

var value = $("#myDiv").data('value');

Solution 3

In my asp.net I am not getting the result by

     <script type="text/javascript">
          var someSessionVariable = '@Session["SomeSessionVariable"]';
     </script>

But I get the answer by below code,

<script type="text/javascript">

     var yourVariable = '<%= Session["SessionKey"] %>';

</script>
Share:
75,851

Related videos on Youtube

Roy Justin
Author by

Roy Justin

Updated on July 09, 2022

Comments

  • Roy Justin
    Roy Justin almost 2 years

    I wanted to access a session variable in javascript in asp.net mvc application. I have found a way to do it in aspx view engine but not in razor.

    Please tell me a way to access the session variables

    • Admin
      Admin over 10 years
      Have you tried adding the session value to a model?
  • Burak Karakuş
    Burak Karakuş almost 10 years
    How can I access and get the value of this session from my Controller?
  • Moeri
    Moeri almost 10 years
    In any MVC or Web API controller, you can just type var myValue = Session["MyKey"]; to get the value for "MyKey"
  • Burak Karakuş
    Burak Karakuş almost 10 years
    Thank you so much, I'll try that.
  • Nagaraj Pujar
    Nagaraj Pujar over 6 years
    I think, you haven't used MVC in your application.

Related