【问题标题】:How to set JavaScript variable to ASP.NET Session?如何将 JavaScript 变量设置为 ASP.NET 会话?
【发布时间】:2019-04-24 18:22:03
【问题描述】:

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

function getCheckboxVal(el)
{
    var price = el.getAttribute("Price");
    '<%Session["Price"] = "' + price +'"; %>';
}

【问题讨论】:

  • 为什么要用JS来设置那个会话变量?
  • 会话变量在服务器上设置和维护。您无法使用 JavaScript 直接访问它们。要在 JavaScript 中设置/获取 Session 变量的值,您需要使用对服务器的 AJAX 调用来设置/获取值并将其返回给 JavaScript 代码的脚本。
  • 不,不是@JohnB,您可以在 javascript 中访问它
  • ajax 是一种设置服务器端的方法。下面的答案是使用另一种技术来设置控件的值。这些都没有减损你不正确的事实。试图将论点转移到其他东西上是徒劳的。我支持我的第一条评论Session variables are set and maintained on the server. You cannot access them directly with JavaScript.

标签: javascript c#


【解决方案1】:

我们不能直接将客户端值设置为会话。我们可以通过使用隐藏文件来做到这一点

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

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

Session["PriceData"] = hdPrice;

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    您不能直接从 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"];
    

    【讨论】:

      【解决方案3】:

      由于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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-21
        • 2016-05-10
        • 2017-07-08
        • 2015-03-11
        • 2016-11-21
        • 2016-03-15
        • 1970-01-01
        相关资源
        最近更新 更多