在我的 viewModel 中,我想获取当前会话值。为此,我这样写:
self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);
但它向我展示了错误
ReferenceError: HttpContext is not defined.
如何定义 HttpContext?或者有什么方法可以获取当前会话值?
在我的 viewModel 中,我想获取当前会话值。为此,我这样写:
self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);
但它向我展示了错误
ReferenceError: HttpContext is not defined.
如何定义 HttpContext?或者有什么方法可以获取当前会话值?
改变你的陈述
self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);
如果您 使用 webform 和 viewmodel 的应用程序与 aspx 页面内联
self.currentUserId = ko.observable('<%=HttpContext.Current.Session["UserID"]%>');
如果 MVC 带有带有视图的内联视图模型的剃刀视图引擎
self.currentUserId = ko.observable('@HttpContext.Current.Session["UserID"]');
如果您的视图模型在外部 js 文件中,则首先将其存储在 js 变量中并在该 js 中使用
比如,你不能HttpContext.Current.Session["UserID"]
在外部 js 文件中使用。
<script type="text/javascript" src='<path_of_knochout.js>'></script>
<script type="text/javascript">
var userId = '<%=HttpContext.Current.Session["UserID"] %>';
</script>
<script type="text/javascript" src='<your_view_model_js>'></script>
在<your_view_model_js>
文件使用中
self.currentUserId = ko.observable(userId);