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
1 Answer
Reset to default 5Change 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);