Can you access Session Variables from Client Side Script?

  • Thread starter Thread starter Craig G
  • Start date Start date
No, you have to pass them to client, for example in a hidden input element.

Eliyahu
 
Craig said:
if so, how?
You cannot access Session directly from client side script. However, you
can generate JavaScript code to assign the value of the Session variable
to a client side variable. If you change the client side variable,
you'll have to post the new value back in order to update the Session.

Here is a simple example which creates a JavaScript variable with the
value of a Session variable:
<%@ Page language="c#" AutoEventWireup="true" %>
<script runat="server">
void Page_Load()
{
Session["MySessionVar"]="Hello world";
}
</script>
<html>
<script language="JavaScript">
var mySessionVar="<%= Session["MySessionVar"] %>";
</script>
<body>
<form runat="server"></form>
</body>
</html>

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
nice one, cheers for the help!

Anders Norås said:
Craig said:
if so, how?
You cannot access Session directly from client side script. However, you
can generate JavaScript code to assign the value of the Session variable
to a client side variable. If you change the client side variable,
you'll have to post the new value back in order to update the Session.

Here is a simple example which creates a JavaScript variable with the
value of a Session variable:
<%@ Page language="c#" AutoEventWireup="true" %>
<script runat="server">
void Page_Load()
{
Session["MySessionVar"]="Hello world";
}
</script>
<html>
<script language="JavaScript">
var mySessionVar="<%= Session["MySessionVar"] %>";
</script>
<body>
<form runat="server"></form>
</body>
</html>

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
Back
Top