locked
Retrieve Session Variable value in a javascript file RRS feed

  • Question

  • User1291657044 posted

    I have an asp.net web page with a session variable defined in the code (Session["sessionValue"] = value;). I also have a javascript file that has a bunch of functions and want to access the session variable in the file (clientfile.js). How do i do that? I tried to directly access it as i would in another web page (string value = Session['sessionValue"];) but it's returning no value. Any suggestions?

    I also can go with the below code in the asp.net code behind. But again, how do i access the session value in an external js file? 

        <script type="text/javascript">

            var sessionValue = '<%= Session["currentDate"] %>';
            alert(sessionValue);

    </script>

    Tuesday, November 14, 2017 4:47 PM

Answers

  • User-707554951 posted

    Hi eyobzeleke,

    Yes, of course,

    Something as below:

    window.onload = function () {
        var sessionValue = document.getElementById("session").value;
        getsessionValueinthis(sessionValue)
    }
    function getsessionValueinthis(sessionValue) {
    
        alert(sessionValue)
    }

    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 16, 2017 3:13 AM

All replies

  • User475983607 posted

    eyobzeleke

    I have an asp.net web page with a session variable defined in the code (Session["sessionValue"] = value;). I also have a javascript file that has a bunch of functions and want to access the session variable in the file (clientfile.js). How do i do that? I tried to directly access it as i would in another web page (string value = Session['sessionValue"];) but it's returning no value. Any suggestions?

    I also can go with the below code in the asp.net code behind. But again, how do i access the session value in an external js file? 

        <script type="text/javascript">

            var sessionValue = '<%= Session["currentDate"] %>';
            alert(sessionValue);

    </script>

    It's not possible as .js files are not processed by the ASP.NET framework. One method is to craft an ASPX page that renders JavaScript.

    An easier method, IMHO, is to assigned the variable from the current page or better yet design the JavaScript app to accept a constructor or property.

    This example uses the global approach and sets the global variable found in the site.js file from the ASPX page.  

    site.js

    var sessionValue = "Hello World!";
    function showSessionValue()
    {
        return sessionValue;
    }

    ASPX page

            protected void Page_Load(object sender, EventArgs e)
            {
                Session["currentDate"] = DateTime.Now.ToString();
            }
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo._default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Default</title>
        <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
        <script src="js/site.js"></script>
        <style>
        </style>
        <script>
            $(function () {
                sessionValue = '<% =Session["currentDate"] %>'
                //console.log(showSessionValue());
                alert(showSessionValue());
            });
    
        </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
          
        </form>
    </body>
    </html>
    
    
    
    


    JavaScript looks for variables in global scope if a variable is not declared with var as shown in the ASPX page.  Since there is a var in global scope with the same name as the one found in the ASPX page (due to the site.js file reference) the global var sessionValue is assigned to the Session variable from the ASP page.  

    This is not a "good" design but it seems that you are already using global variables so this approach should work.

    Tuesday, November 14, 2017 7:30 PM
  • User1291657044 posted

    Thanks mgebhard for the example. I want to clarify though the sessionValue you have in the code behind (ASPX page), that's the value i want to access from with in the site.js page. I have a hyperlink in a function that needs the sessionValue. See what I mean?

    Tuesday, November 14, 2017 8:33 PM
  • User475983607 posted

    eyobzeleke

    Thanks mgebhard for the example. I want to clarify though the sessionValue you have in the code behind (ASPX page), that's the value i want to access from with in the site.js page. 

    JavaScript is like an application loaded in the browser.  If the ASPX has a reference to the .js file and the .js file has a global variable then simply set the global variable from the ASPX page.

    Not like this...

    <script type="text/javascript">
    	var sessionValue = '<%= Session["currentDate"] %>';
    	alert(sessionValue);
    </script>

    Like this without the var.

    <script type="text/javascript">
    	sessionValue = '<%= Session["currentDate"] %>';
    	alert(sessionValue);
    </script>

    I have a hyperlink in a function that needs the sessionValue. See what I mean?

    I understand the words but without code I have no idea what you're doing.  Perhaps you need to create a constructor to initialize the function with the hyperlink.

    Is there anyway you can post your code or at least an example?

    Tuesday, November 14, 2017 10:05 PM
  • User1291657044 posted

    Yes, here is my code:

    ASPX:

     <script type="text/javascript">
            sessionValue = '<%= Session["currentDate"] %>';        
        </script>
        <script type="text/javascript" src="./Scripts/calendarscript.js"></script>

    calendarscript.js:

    var calendar = $('#calendar').fullCalendar({
    dayClick: function (date, jsEvent, view) {
    	window.location = "http://Test?Date=" + ((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
    
    },      
    theme: true,       
    header: {
    	left: 'prev,next today',
    	center: 'title',
    	right: 'month,agendaWeek,agendaDay'
    },        
    
    eventClick: updateEvent,
    selectable: true,
    selectHelper: true,
    select: selectDate,
    editable: true,
    events: "JsonResponse.ashx",
    eventDrop: eventDropped,
    eventResize: eventResized,        
    eventRender: function(event, element) {
    } 
    	element.qtip({
    		content: event.description,
    		position: { corner: { tooltip: 'bottomLeft', target: 'topRight'} },
    		style: {
    			border: {
    				width: 1,
    				radius: 3,
    				color: '#2779AA'
    
    			},
    			padding: 10,
    			textAlign: 'center',
    			tip: true, // Give it a speech bubble tip with automatic corner detection
    			name: 'cream' // Style it according to the preset 'cream' style
    		}
    
    	});
    }
    });
    var cur = sessionValue;    
    $('#calendar').fullCalendar('gotoDate', cur.getFullYear(), cur.getMonth(), cur.getDate());

    It is the last 2 lines i am interested in. Unfortunately, I couldn't get the value out of sessionValue to be read in the js file. However, if i create a quick function in the js file and call it in the aspx page with Alert(function), I get the value of sessionValue. Any idea?

    Tuesday, November 14, 2017 11:07 PM
  • User475983607 posted

    eyobzeleke

    I get the value of sessionValue. Any idea?

    Order matters in JavaScript.  Basically, the JavaScript code needs to be refactoring.  IMHO, having a hard coded selector in an external .js file is not an optimal design.  I would forget the external file and get the calendar working as expected in the ASPX page  Then look at moving to an external file.

    Tuesday, November 14, 2017 11:53 PM
  • User-707554951 posted

    Hi eyobzeleke,

    Keep in mind, Session is not available in .js file. It can be access from your apsx page only.

    For your problem, i think you could try to write your session value to a hidden html element and read value of this hidden element with javascript as follow :

    <input type="hidden" id="session" value="<%=Session["Test"]%>"/>

    In site.js, you coudl do like this:

    window.onload = function () {
        var sessionValue = document.getElementById("session").value;
        alert(sessionValue);
    }

    Best regards

    Cathy

    Wednesday, November 15, 2017 8:18 AM
  • User1291657044 posted

    Thanks for the info Cathy! Ffrom your example, would sessionValue be accessible by other functions in the site.js file?

    Thursday, November 16, 2017 3:02 AM
  • User1291657044 posted

    Thanks mgebhard for your help! 

    Thursday, November 16, 2017 3:05 AM
  • User-707554951 posted

    Hi eyobzeleke,

    Yes, of course,

    Something as below:

    window.onload = function () {
        var sessionValue = document.getElementById("session").value;
        getsessionValueinthis(sessionValue)
    }
    function getsessionValueinthis(sessionValue) {
    
        alert(sessionValue)
    }

    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 16, 2017 3:13 AM
  • User1291657044 posted

    Thank you Cathy!

    Friday, November 17, 2017 3:10 PM