0

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.

1

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.