【问题标题】:Access js localStorage stored value in VB.Net在 VB.Net 中访问 js localStorage 存储的值
【发布时间】:2013-03-08 08:46:16
【问题描述】:

我有一个登录页面,它将一些值存储到 localStorage (html5),然后继续到 VB.Net 页面。我正在寻找一种在 VB 中可以读取这些存储值并使它们成为 VB vars 的方法。有什么想法吗?

【问题讨论】:

    标签: vb.net html local-storage


    【解决方案1】:

    VB.NET 代码隐藏在服务器上运行,无法直接访问浏览器的本地存储 API。

    但是,您可以使用 JavaScript 轻松填充登录页面上的一些隐藏字段,这些字段将在提交时发布,并且可以从 .NET 页面的代码隐藏中读取。

    类似这样的东西(未测试):

    this.document.getElementById("HIDDEN_FIELD_ID").value = localStorage.STORED_VALUE;
    ...
    <input type="hidden" id="HIDDEN_FIELD_ID" />
    ...
    

    在 .NET 页面上,值可以这样读取:

    Request.Form("HIDDEN_FIELD_ID")

    (还有其他方法,但是这个很容易掌握。)

    请注意,用户可以访问(和修改)localStorage 中的登录数据,因此请确保不会造成安全风险。

    【讨论】:

      【解决方案2】:

      此示例将上述概念与 VB 代码一起使用:

      这里是html正文元素:

      <body>
      <form id="form1" runat="server">
      <asp:HiddenField ID="hfLoaded" runat="server" />
      <asp:HiddenField ID="hfLocalStorage" runat="server" />
      </form>
      <script type="text/javascript">
          // Load LocalStorage
          localStorage.setItem('strData', 'Local storage string to put into code behind');
      
      
          function sendLocalStorageDataToServer()
          {
              // This function puts the localStorage value in the hidden field and submits the form to the server.
              document.getElementById('<%=hfLocalStorage.ClientID%>').value = localStorage.getItem('strData');
              document.getElementById('<%=form1.ClientID%>').submit();
          }
      
          // This checks to see if the code behind has received the value. If not, calls the function above.
          if (document.getElementById('<%=hfLoaded.ClientID%>').value != 'Loaded')
              sendLocalStorageDataToServer();
      </script>
      

      这是页面加载事件:

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
          Dim s As String
          s = hfLocalStorage.Value
      
          'This next line prevents the javascript from submitting the form again.
          hfLoaded.Value = "Loaded"
      End Sub
      

      现在您的代码后面有可用的 localStorage 值。

      【讨论】:

        猜你喜欢
        • 2018-12-13
        • 2018-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 1970-01-01
        相关资源
        最近更新 更多