最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Session value in knockout - Stack Overflow

matteradmin4PV0评论

In my viewModel i want to get the current session value. For that i have written like this :

self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);

But its showing me error that

ReferenceError: HttpContext is not defined.

How to define HttpContext? OR Is there any way to get current session value?

In my viewModel i want to get the current session value. For that i have written like this :

self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);

But its showing me error that

ReferenceError: HttpContext is not defined.

How to define HttpContext? OR Is there any way to get current session value?

Share Improve this question asked Nov 1, 2012 at 8:35 akeesethakeeseth 8452 gold badges16 silver badges33 bronze badges 2
  • 1 What technology do you use? Webforms or MVC? What is your view engine: aspx, razor? Your ko viewmodel is inlined in your view or it is in a separate js file? – nemesv Commented Nov 1, 2012 at 8:37
  • I am using webforms with aspx view engine. My viewmodel is in separate js file. – akeeseth Commented Nov 1, 2012 at 8:42
Add a ment  | 

1 Answer 1

Reset to default 5

Change your statement

self.currentUserId = ko.observable(HttpContext.Current.Session["UserID"]);

To If your application using webform and viewmodel is inline with aspx page

self.currentUserId = ko.observable('<%=HttpContext.Current.Session["UserID"]%>');

if MVC with razor view engine with inline viewmodel of view

self.currentUserId = ko.observable('@HttpContext.Current.Session["UserID"]');

and if your viewmodel is in external js file, then first store it in a js variable and use in that js

like, you can't use HttpContext.Current.Session["UserID"] in external js file.

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

in <your_view_model_js> file use

self.currentUserId = ko.observable(userId);
Post a comment

comment list (0)

  1. No comments so far