代码之家  ›  专栏  ›  技术社区  ›  batwing

如何将javascript变量设置为ASP.NET会话?

  •  0
  • batwing  · 技术社区  · 7 年前

    如何将javascript变量设置为ASP.NET会话?当前,价格中的值不存储在会话中,而是存储字符串“'+price+'”。如何存储价格变量的值?

    function getCheckboxVal(el)
    {
        var price = el.getAttribute("Price");
        '<%Session["Price"] = "' + price +'"; %>';
    }
    
    3 回复  |  直到 7 年前
        1
  •  5
  •   Ambrish Pathak    7 年前

    您不能直接从JS设置会话,因为会话存储在服务器上,JS在客户端运行。

    您可以为此目的使用隐藏输入,例如:

    <input  type='hidden' id='Price' name='Price'/>
    
    var price = el.getAttribute("Price"); //Populate price var as required
    var h=document.getElementById('Price'); 
    h.value=price; //set hidden input's value
    

    然后得到这个 var price 要从代码隐藏设置会话,请执行以下操作:

    Session["TestSession"] = Request.Form["Price"];
    
        2
  •  2
  •   Tetsuya Yamamoto    7 年前

    自从 Session 状态在服务器端维护,不能直接从客户端分配。可以对服务器端Web方法执行Ajax回调,该方法稍后存储会话状态值:

    [WebMethod(EnableSession = true)]
    public void SetPrice(string value) 
    {
        if (Session != null)
        {
            Session["Price"] = value;
        }
    }
    
    function getCheckboxVal(el) {
        var price = el.getAttribute("Price");
        $.ajax({
            type: 'POST',
            url: 'Page.aspx/SetPrice',
            data: { value: price },
            success: function (data) {
                // do something
            }
    
            // other AJAX settings
        });
    }
    

    或使用隐藏字段 runat="server" 属性并指定其值,使其进入代码隐藏状态:

    ASPX公司

    <asp:HiddenField ID="HiddenPrice" runat="server" />
    
    <script>
        function getCheckboxVal(el) {
            var price = el.getAttribute("Price");
    
            document.getElementById('<%= HiddenPrice.ClientID %>').value = price;
        }
    </script>
    

    代码落后

    Session["Price"] = HiddenPrice.Value.ToString();
    

    参考文献: Accessing & Modifying Session from Client-Side using JQuery & AJAX in ASP.NET

        3
  •  0
  •   Bharati Mathapati    7 年前

    我们不能直接将clientside值设置为session。我们可以通过使用隐藏文件

    <asp:HiddenFieldID="hdPrice" runat="server" /> 
    

    进一步获得这个JS价格并在javascript中设置为变量hprice。 可以将此变量添加到会话中

    Session["PriceData"] = hdPrice;
    

    希望这对你有帮助。