locked
Issue with Session variable in javascript RRS feed

  • Question

  • User1016820894 posted

    I have the code below set up in asp.net and code behind. I initially set the session to 0 and then increase by 1 each time the page is refreshed.

    The first time through it works fine. The first alerts show 0 for session variable and 1 for local. The second set of alerts then shows 1 for both (which indicates that the session variable is being updated).

    When the page is refreshed it bombs off when it tries to set the session variable to the local (under the try/catch). I tried debugging at that point but it seems to skip over that code so I can't see the error. Interestingly if I flag that out (OR if I assign a hard -coded value to the session variable) it then works. I am confused as to why it doesn't work consistently.  

    Code Behind:

            if (Session["refreshcount"] == null)
            {
                Session["refreshcount"] = 0;
            }


    ASP.NET:

     <script type="text/javascript">
     
            localrefreshcount = '<%=Convert.ToInt32(Session["refreshcount"])%>';
            localrefreshcount++;
           
            alert("Session Refresh Count: " + '<%=Session["refreshcount"]%>');
            alert("Local Refresh Count: " + localrefreshcount);

            if (localrefreshcount == 2)
            {
                localrefreshcount = 0;  
            }
           
            try {
                <%Session["refreshcount"] = "'+ localrefreshcount +'";%>
            }
            catch (e) {
                alert(e);
            }
          
            alert("Session Refresh Count: " + '<%=Session["refreshcount"]%>');
            alert("Local Refresh Count: " + localrefreshcount);

    </script>

    Thursday, May 10, 2018 12:39 PM

All replies

  • User475983607 posted

    baldwinjohn

    When the page is refreshed it bombs off when it tries to set the session variable to the local (under the try/catch). I tried debugging at that point but it seems to skip over that code so I can't see the error. Interestingly if I flag that out (OR if I assign a hard -coded value to the session variable) it then works. I am confused as to why it doesn't work consistently.  

    Correct, and the expected behavior.  The ASP code runs first.  The results of the ASP code and variables are sent to the browser in the response stream.  A POST or GET is required to send data (request stream) from the browser to the server. 

    Thursday, May 10, 2018 2:37 PM
  • User1016820894 posted

    Ok. I am fairly new to asp.net programming. Can you provide some examples on how to do that?

    Thanks!

    Thursday, May 10, 2018 3:11 PM
  • User475983607 posted

    baldwinjohn

    Ok. I am fairly new to asp.net programming. Can you provide some examples on how to do that?

    Thanks!

    It's much easier to provide assistance if the problem is explained. 

    JavaScript variables cannot keep track of full refreshes because a refresh - well - refreshes the page with new content which includes JavaScript. 

    This sample sends an AJAX request to the server.  Session is set to 0 if the count is greater than 1.

    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    
    namespace WebFormsDemo
    {
        public partial class _default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    if (Session["refreshcount"] == null)
                    {
                        Session["refreshcount"] = 0;
                    }
                    else
                    {
                        Session["refreshcount"] = (int)Session["refreshcount"] + 1;
                    }
                }
            }
    
            [WebMethod(EnableSession = true)]
            public static int SetSession(int localrefreshcount)
            {
                HttpContext.Current.Session["refreshcount"] = localrefreshcount;
                return localrefreshcount;
            }
        }
    }
    <%@ 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-1.12.4.js"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="result"></div>
        </form>
    
        <script>
            $(function () {
    
                var localrefreshcount = <%=Session["refreshcount"]%>;  
    
                write("Local Refresh Count: " + localrefreshcount);
    
    
                if (localrefreshcount > 1) {
    
                    var data = {};
                    data.localrefreshcount = 0;
    
                    $.ajax({
                        url: 'default.aspx/SetSession',
                        type: 'POST',
                        data: JSON.stringify(data),
                        contentType: 'application/json;utf-8',
                        datatype: 'json'
                    }).done(function (data) {
                        write("Ajax Session Reset: " + data.d);
                    }).fail(function (data) {
                        console.log("Error: " + data);
                    });
                }
    
                function write(content) {
                    $('#result').append($('<div>' + content + '</div>'));
                }
    
            });
    
    
    
        </script>
    </body>
    </html>
    
    
    
    

    Thursday, May 10, 2018 5:35 PM