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
Solution 1:
You can do it this way for a String
variable:
<scripttype="text/javascript">var someSessionVariable = '@Session["SomeSessionVariable"]';
</script>
Or like this if it's numeric:
<scripttype="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
<scripttype="text/javascript">var someSessionVariable = '@Session["SomeSessionVariable"]';
</script>
But I get the answer by below code,
<scripttype="text/javascript">var yourVariable = '<%= Session["SessionKey"] %>';
</script>
Solution 4:
For google searchers,
In addition, If you want to access the session variable in external .js
file you can simply do like this,
------ SOMEHTMLPAGE ------
//Scripts below Html page<script>//Variable you want to accessvar mySessionVariable = '@Session["mySessionVariable"]';
</script>// Load External Javascript file<scriptsrc="~/scripts/MyScripts/NewFile.js"></script>
Inside NewFile.js
$(document).ready(function () {
alert(mySessionVariable);
});
Post a Comment for "Access Session Variables In Javascript"