如何使用Knockout从vm设置会话变量?

时间:2013-09-05 13:50:42

标签: javascript asp.net vb.net session knockout.js

我已经看到了一些关于如何将一个Session变量转换为knockout的问题,但没有一个解释如何从Knockout vm中设置一个。我的设置:

-ASPX页面,我得到一个Session [“GridSize”]变量,并将其作为一个名为currentGridSize的全局变量返回

-VM我得到那个全局变量,并设置this.gridSize = globals.gridSize

-Dropdown改变this.gridSize

我需要什么:

- 设置Session [“GridSize”] = this.gridSize的一些方法,无论是更改还是页面保留

我试过了:

- 在我的.aspx.vb上使用webmethod函数并调用它(无法从Shared函数调用Session变量,并且必须共享webmethods)

-Calling<%Session [“CurrentPageIndex”] = self.currentPageIndex();%>来自vm

1 个答案:

答案 0 :(得分:1)

您可以通过对页面方法执行以下操作来访问ASP.NET AJAX页面方法中的Session

<WebMethod(EnableSession := True)> _
Public Shared Sub StoreSessionValue(sessionValue As String)
    ' Set a value into Session
    HttpContext.Current.Session("TheSessionValue") = sessionValue
End Sub

<WebMethod(EnableSession := True)> _
Public Shared Function GetSessionValue(sessionValueName As String) As String
    ' Get a value from Session
    Return HttpContext.Current.Session(sessionValueName)
End Sub

注意:您必须将Session对象完全限定为HttpContext.Current.Session

您可以在视图模型函数中调用此页面方法,如下所示:

$.ajax({
  type: "POST",
  url: "YourPage.aspx/GetSessionValue",
  data: "{'sessionValueName':'sessionValue'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
    // Do something with data returned here

  }
});