Click here to Skip to main content
15,905,912 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In am aspx.cs, I created a session variable:
C#
Session["test"] = "sss";

In another open page, I want to retrieve the value of the session variables in JS through
C#
var s = '@Session["test"]';
var s2 = '<%= Session["test"] %>';  // got s2 value: <%=@Session["test"]%>
var s3 = '<%= session.getAttribute["test"] %>';

But got nothing. What should I do to retrieve the session variable's value? Thanks.
Posted
Updated 12-Jan-16 5:19am
v4

You need to understand the asp.net page lifecycle. What your code is doing is generating html when it is first requested from the server and sending that static html to the client. So if you had "Hello" in Session["test"] when the page was requested then it would generate the following js;

JavaScript
var s = 'Hello';


That is what is executed in the browser so if the Session variable is amended elsewhere that change is not going to reflect in your original page until that page is refreshed, as your .net code isn't "running inside" the browser, it is only used to generate the initial html to send to the browser.
 
Share this answer
 
Comments
s yu 12-Jan-16 11:25am    
F-ES: Thanks for your response. Could you explain more since I could not follow well. What is wrong in my app? In my 2nd page (a html file), why I could not retrieve the session variable created in the .aspx.cs? In the Html page, if I click on a button, how can this page be refreshed? Thanks.
F-ES Sitecore 12-Jan-16 11:28am    
The code you are posting will only work if the page has been processed by asp.net. If it's an html page then no asp.net code is executed on it. You'll need to make it an aspx page rather than an html one.
Sergey Alexandrovich Kryukov 12-Jan-16 12:20pm    
5ed.
—SA
Your second solution will do. please see links to update your solution:

Possible to get session value in javascript[^]

asp.net - Getting session value in javascript - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900