且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript指定会话值

更新时间:2023-12-04 18:46:40

尝试使用Ajax调用设置会话值: -

JS: -

 <脚本SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js> < / SCRIPT>
<脚本类型=文/ JavaScript的>
    VAR TempSession ='<%= Convert.ToInt32(会话[状态])%GT;';
    如果(TempSession == 6){
        警报(TempSession);
        $阿贾克斯({
            输入:POST,
            网址:'WebForm1.aspx的/的SetValue,
            数据:{VAL:1},
            的contentType:应用/ JSON的;字符集= UTF-8,
            数据类型:JSON,
            成功:函数(MSG){
                警报(新建会话值+ msg.d);
            }
        });
    }< / SCRIPT>

在隐藏文件中的code: -

  [的WebMethod]
公共静态字符串的SetValue(字符串VAL)
{
    HttpContext.Current.Session [状态] = VAL;
    返回HttpContext.Current.Session [状态]的ToString()。
}

Is there any way to assign session value using javascript

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

var TempSession = '<%= Convert.ToInt32(Session["Status"]) %>';
if(TempSession ==6)
{
   alert(TempSession );
   TempSession =1;
}

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();
}