I have a scenario where I open my web application in a browser but in two separate tabs.
In one tab I signed out from the application and as a result the all session val
Accessing & Assigning the Session Variable using Javascript:
Assigning the ASP.NET Session Variable using Javascript:
<script type="text/javascript">
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Already Answered here
Take hidden field with id or class and value with session and get it in javascript.
Javascript var session = $('#session').val(); //get by jQuery
would be a lot easier to use Razor code in your page.
in my example, i needed to set a hidden field with a session variable.
$('#clearFormButton').click(function(){
ResetForm();
$('#hiddenJobId').val(@Session["jobid"]);
});
that easy. remember, you need to preface the Session with a @ sign for razor syntax.
this is how i used ->
<body onkeypress='myFunction(event)'>
<input type='hidden' id='homepage' value='$_SESSION[homepage]'>
<script>
function myFunction(event){var x = event.which;if(x == 13){var homepage
=document.getElementById('homepage').value;
window.location.href=homepage;}else{
document.getElementById("h1").innerHTML = "<h1> Press <i> ENTER </i> to go back... </h1>";}}
</script>
</body>
Another approach is in your chtml
<input type="hidden" id="hdnSession" data-value="@Request.RequestContext.HttpContext.Session['someKey']" />
and the script is
var sessionValue= $("#hdnSession").data('value');
or you may access directly by
jQuery(document).ready(function ($) {
var value = '@Request.RequestContext.HttpContext.Session["someKey"]';
});
try like this
var username= "<%= Session["UserName"]%>";