[javascript] 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 that javascript. How can i get the session value in that javascript file?

Thanks in advance..

This question is related to javascript asp.net session

The answer is


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

the text in single quotes will give session value. 1)

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

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

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

//and in script you access the hiddenfield  like

alert(document.getElementbyId("hiddenfield").value);

var sessionVal = '@Session["EnergyUnit"]';
alert(sessionVal);

I tried following with ASP.NET MVC 5, its works for me

var sessionData = "@Session["SessionName"]";

For me this code worked in JavaScript like a charm!

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

hope it helps...


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>

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?