Getting session value in javascript

I am using an external javascript file for my asp.net project. Now I want to get the session value in this javascript. How can I get the session value in this javascript file?

Thanks in advance.

+7
source share
6 answers
<script> var someSession = '<%= Session["SessionName"].ToString() %>'; alert(someSession) </script> 

This code can be written to Aspx. If you want this in some js.file, you have two ways:

  • Create an aspx file that writes the full JS code and set the source of this file as Script src
  • Make a handler, process the JS file as aspx.
+17
source

You can access your session variable as '<% = Session ["VariableName"]%>'

single quoted text will give the value of the session. one)

 <script> var session ='<%= Session["VariableName"]%>' </script> 

2) you can take a hidden field and assign a value on the server;

hiddenfield.value = session ["xyz"]. tostring ();

 //and in script you access the hiddenfield like alert(document.getElementbyId("hiddenfield").value); 
+5
source

For me, this code worked in JavaScript like a charm!

 <%= session.getAttribute("variableName")%> 

hope this helps ...

0
source
 protected void Page_Load(object sender, EventArgs e) { Session["MyTest"] = "abcd"; String csname = "OnSubmitScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the OnSubmit statement is already registered. if (!cs.IsOnSubmitStatementRegistered(cstype, csname)) { string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; "; cs.RegisterOnSubmitStatement(cstype, csname, cstext); } if (TextBox1.Text.Equals("")) { } else { Session["MyTest"] = TextBox1.Text; } } <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script language=javascript type="text/javascript"> function getMyvalSession() { var txt = "efgh"; var ff = '<%=Session["MyTest"] %>' + txt; return ff ; } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox> <input type="submit" value="Submit" /> </div> </form> </body> </html> 
0
source
 var sessionVal = '@Session["EnergyUnit"]'; alert(sessionVal); 
0
source

If you use VB code as a code, you need to use the bracket β€œ()” instead of the square bracket β€œ[]”.

Example for VB:

 <script type="text/javascript"> var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>'; </script> 
0
source

All Articles