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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 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');
Method 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>
Method 4
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);
});
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0