13

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

1
  • 1
    Have you tried adding the session value to a model? Commented Jan 7, 2014 at 13:30

4 Answers 4

26

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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');

2 Comments

How can I access and get the value of this session from my Controller?
In any MVC or Web API controller, you can just type var myValue = Session["MyKey"]; to get the value for "MyKey"
1

For google searchers,

In addition, If you want to access the session variable in external .js file you can simply do like this,

------ SOME HTML PAGE ------

//Scripts below Html page
<script>   
    //Variable you want to access
    var mySessionVariable = '@Session["mySessionVariable"]';
</script>

// Load External Javascript file
<script src="~/scripts/MyScripts/NewFile.js"></script> 

Inside NewFile.js

$(document).ready(function () {
    alert(mySessionVariable);
});

Comments

1

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>

1 Comment

I think, you haven't used MVC in your application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.