Assign session value using javascript

后端 未结 4 1217
一生所求
一生所求 2020-12-19 21:36

Is there any way to assign session value using javascript

i can retrive the value from session but assigning is not working

var TempSession = \'<%         


        
相关标签:
4条回答
  • 2020-12-19 22:20

    You can transfer data to the server session by sending it through a XmlHttpRequest. The page or handler that recieves this data can put it in the server session data collection.

    0 讨论(0)
  • 2020-12-19 22:21

    If you're talking about server-side session then it really depends on the server-side.

    It should assign you a session id, usually through a cookie....
    That means you could for example make an ajax request to a designated url in your server, specifying the required session id. That ajax request would then assign the session through a cookie.

    Another idea would be to actively create a cookie (again, if server supports that) on the client-side with JavaScript with specific session id, i.e

    $.cookie("SESSION", "session-id"); // Using jQuery
    

    Although I've never tried that before.
    Note above that the cookie's name depends on your server technology (Tomcat is JSESSIONID by default [link], ASP.NET is ASP.NET_SessionId [link], under "Note").

    0 讨论(0)
  • 2020-12-19 22:27

    Try using ajax call for setting the session value:-

    JS:-

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
    <script type="text/javascript">
        var TempSession = '<%= Convert.ToInt32(Session["Status"]) %>';
        if (TempSession == 6) {
            alert(TempSession);
            $.ajax({
                type: 'POST',
                url: 'WebForm1.aspx/SetValue',
                data: '{ val:1 }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (msg) {
                    alert("New Session value is " + msg.d);
                }
            });
        }
    
    </script>
    

    In your code behind file:-

    [WebMethod]
    public static string SetValue(string val)
    {
        HttpContext.Current.Session["Status"] = val;
        return HttpContext.Current.Session["Status"].ToString();
    }
    
    0 讨论(0)
  • 2020-12-19 22:38

    Actually there this a tutorial on MSDN that covers you case. It is described in Exposing Web Services to Client Script, see "Calling Static Methods in an ASP.NET Web Page" section.

    All you have to do is to set EnablePageMethods property to True on your ScriptManager control, then using PageMethods object call static method (it should be decorated with WebMethod attribute) declared in code behind.

    0 讨论(0)
提交回复
热议问题