javascriptc#asp.netsessionasplinkbutton

How to pass session value from aspx (stored using javascript) to cs


I am able to store the session variable in aspx page using the following way :

  $(document).ready(function () {
            var userName = "webruster";
            '<%Session["UserName"] = "' + userName + '"; %>';
           alert('<%=Session["UserName"]%>');
        });

now when i am trying to retrieve the Session["UserName"] i am unable to get that value in cs . For this i have a work around but want to know the reason why it is failing ?

Alternative way :

Declaring hidden Variable and Link button

$(document).ready(function () {
            var userName = "webruster";
            '<%Session["UserName"] = "' + userName + '"; %>';
            var x = document.getElementById("<%=hdnsessionvalue.ClientID %>");
            x.value = '<%=Session["UserName"] %>';

           document.getElementById('<%= lnkButton1.ClientID %>').click();
        });

So i am able to retrieve the value in onclick event in server side.

My question : So why i am unable to retrieve the session value in cs using the first method (i.e without assigning to hidden variable)


Solution

  • If you mean 'client side java script' then you can't, at least not directly. The session data is stored on the server and client side doesn't see it without communicating with server.

    To access it can make an HTTP request and have server side modify or return the data.

    Updated

    Example

    <script>
           // get the variable
           var data = JSON.Stringify(yourVariable);
    
           // Make the ajax call
           $.ajax({
             type: "POST",
             url: "aspPage.aspx/Method", //method we will call
             contentType: "application/json; charset=utf-8",
             data: {value: data }, //assign the 'data' values to 'value', its the data you want to send 
             dataType: "json",
             success: function (result) {
                 alert('its working');               
             },
             error: function (result) {
                 alert('something wrong');
             }
         });
      </script>
    

    on aspPage.aspx

    [WebMethod]
    public static void Method(string value)
    {
      sting val = value; // Do whatever you want to 
    }