I need to access a Session Variable in javascript. I tried all the examples but none of them are working. I do not know what I am doing wrong.
I have the following:
In my Account controller after successful login I set my Session Variable like this.
HttpContext.Session.Add("IsShowStartPopUp", true);
In my landing view I try to access the session variable like this:
<script type="text/javascript">
var IsShowStartPopUp = '<%= Session["IsShowStartPopUp"] %>';
</script>
My result is:
'<%= Session["IsShowStartPopUp"] %>'
Am I missing something?
Thanks you.
In your code, you should not use contention while trying to access a dynamic value '<%= Session["IsShowStartPopUp"] %>' . Otherwise, it'll be considered as a string.
You can use sessionStorage.
Example:
<script>
sessionStorage.setItem('mysession','value');
alert(sessionStorage.getItem('mysession'));
</script>
I found this answer:
No, session state is server-side.
I then use the following:
I still set the session variable in the controller when the user log in
HttpContext.Session.Add("IsShowStartPopUp", true);
I then created the following in my MVC view:
@if (HttpContext.Current.Session["IsShowStartPopUp"].ToString() == true)
{
HttpContext.Current.Session["IsShowStartPopUp"] = false;
<script type="text/javascript">
window.onload = function () {ShowPopup();}
</script>
};
This solved my issue and if there is any suggestions you are more that welcome to comment.
Thanks