Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Session variables in JavaScript

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

like image 869
Roy Justin Avatar asked Jan 07 '14 13:01

Roy Justin


3 Answers

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.

like image 129
Yuck Avatar answered Oct 18 '22 18:10

Yuck


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');
like image 36
Moeri Avatar answered Oct 18 '22 18:10

Moeri


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>
like image 1
shridhar Avatar answered Oct 18 '22 18:10

shridhar