- Back to Home »
- ASP.Net , C# , jQuery , Web Service »
Posted by : Jebastin
Wednesday, 29 January 2014
Usage of Session in ASP.NET using C# or jQuery. A session is a piece of data which is sent from a website and stored locally by the user’s browser. Sessions are needed because HTTP is stateless. This means that HTTP itself has no way to keep track of a user’s previous activities. One way to create state is by using session.
C# Web Service:
- [WebMethod(EnableSession = true)]
- public List<HistoricalProperty> FetchHistoricalData()
- {
- List<HistoricalProperty> historyList = new List<HistoricalProperty>();
- if (Context.Session["historicalData"] != null)
- {
- historyList = (List<HistoricalProperty>)Context.Session["historicalPrice"];
- ...
- ...
- ...
- }
- else
- {
- ...
- ...
- ...
- Context.Session["historicalData"] = historyList;
- }
- return historyList;
- }
jQuery:
TO STORE:
- $(function() {
- $.session.set("myVar", "Hello World!");
- });
TO READ:
- $(function() {
- alert($.session.get("myVar"));
- });
CODE VIEW:
- <!DOCTYPE html>
- <html>
- <head>
- <title>jQuery Session</title>
- <script type='text/javascript' src='jquery-1.9.1.js'></script>
- <script type="text/javascript" src="jquery.session.js"></script>
- </head>
- <body>
- <script type='text/javascript'>
- $(window).load(function() {
- // To Store
- $(function() {
- $.session.set("myVar", "Hello World!");
- });
- // To Read
- $(function() {
- alert($.session.get("myVar"));
- });
- });
- </script>
- </body>
- </html>