Retrieve the session (In List) using javascript - javascript

How to retrieve the session values which are stored in the list using javascript?
I used this code to set the session in the controller.
List<test> _test= new List<test>();
if (Session["testsession"] == null)
Session["testsession"] = _test;
I used this code to retrieve the session list values using javascript
var TEST ='#HttpContext.Current.Session["quotesession"]';
but when i debug it the output is in
var TEST ='System.Collections.Generic.List`1[NLG.IMS.Shared.Models.Test]';
Where i went wrong? I need the session values to be retrieved from the list.

I would advise using a strongly typed model and assigning a property to the collection rather than using session, even the ViewBag would be better but if you really must, this is how you could:
You could use the following:
var json = #Html.Raw(Json.Encode(#HttpContext.Current.Session["quotesession"]));
Which would output it as json.
jsFiddle
The above prints out a collection to the console.log.

Related

Dynamic Array in Local Session

I'm having issues with the logic of using Local session variables. So I understand that HTML5 allows you to set and get these local storage variables.
I've read through this post: adding objects to array in localStorage
and understood that by using SetItem, you will rewrite the variable that you have set and thus for a dynamic array, you will need to get the variable first before pushing a new value.
So the problem I'm having, and I dont't even know if it's possible, is that I want to have, for example, a index.html page which accepts a user input and adds it into an array that needs to be persistent. When the user reloads the same page, the previous input will still be in the same array. From what I read from the post mentioned previously, you will rewrite the variable if you use SetItem. However, if I don't use setItem, how will I be able to specify that the array is to be a local Storage variable... I'm sorry if I confused anyone... because I am quite confused myself. Thanks in advance.
All of your assumptions are correct. You can only write to localStorage using setItem, and when setItem is called, you overwrite whatever value exist there. Therefore, the only way to add an item to an array in localStorage is to get the array from localStorage, manipulate it and then put it back with the new items.
// Check if we already have an array in local storage.
var x = localStorage.getItem("myArray");
// If not, create the array.
if (x === null) x = [];
// If so, decode the array.
else x = JSON.parse(x);
// Add our new item.
x.push("value 1");
// Encode the array.
x = JSON.stringify(x);
// Add back to LocalStorage.
localStorage.setItem("myArray", x);
This could done by the following approach:
var myInput = document.getElementById("myInput").value; // user data
var myList = JSON.parse(localStorage.getItem("myList")); // retrieve the list from LS
if(!Array.isArray(myList)) { // if LS list is not ok, instantiate new array
myList = [];
}
myList.push(myInput); // append user data to the list
localStorage.setItem("myList", JSON.stringify(myList)); // save the list back to LS

How to set data into input type="text" from localstorage array?

I have some troubles trying to put information to a input text, the info is from localstorage:
key=client,value:
[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]
and my question is how can i set the identificacion, firstname, lastname and tel to a inputs type text. Im trying with this jquery
$('#name').val(localStorage.getItem("name"));
but im taking the key, no the values.
Thanks for your help!
this is your localStorage
{client: "[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]", se:fkey: "65d75836cdfe6220e7d8fd44a52ef14e,1438917914"}
to save it to the localStorage Object you need to make any object into a string first
you can do it using JSON.stringify(object)
to save it to your localStorage use localStorage.setItem('key', 'value')
and when you want to fetch it on the localStorage
you can do it using localStorage.getItem('key')
if your item is a json object converted into string
you can make use JSON.parse(string) to bring back to be a json object
First get the data from the localStorage and store them in a variable. Then convert your variable from string to valid JSON format. And finally access the needed data. Here is an example :
var client = JSON.parse(storage.getItem(YOUR_CLIENT_KEY));
...
$('#name').val(client[0].firstname);
Local storage (and session storage) are key/value stores where both the keys and values are strings.
So, when pulling data out of localStorage, it will be a string. In your case, you've stored a JSON object in storage, so to use this as an object, you need to get the string out of localStorage and then use JSON.parse to parse the string and convert it to an object, then you can use the object's properties with your jQuery code:
var data = localStorage.getItem("client");
if(data) {
var obj = JSON.parse(data);
$('#name').val(obj[0].firstName + " " + obj[0].lastName);
}
Be aware that JSON.parse() can throw errors if the string is not valid JSON, so you may want to wrap this call in a try/catch block.
You should log localStorage first to see what is stored in it.
It's weird if the value is
[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]
because only string type can be stored in localStorage. So you may store the array above via:
localStorage.setItem('key', JSON.stringify(array_above));
Do:
var data = JSON.parse(localStorage.getItem('key'));
when you want to retrieve it.
What's more, your code:
$('#name').val(localStorage.getItem('name'));
works fine.
Here is my jsfiddle demo.

Pass multidimensional javascript array between pages

I need to transfer a multi-dimensional JavaScript array to another page, without using any library. What I can use is JavaScript, PHP and other languages that doesn't need a library.
I have a three-dimensional array which is build like this:
storage[category][field][multiple answers] and has a lot of values.
I need to transfer it to another page so I can get all the values like:
alert(storage[5][4][8]);
=======================================================================
Well, I can pass a normal variable to another page but I cant get the values from my array when I'm testing: storage[1][1][1] for example.The big question is how I can pass a multidimensional array to another page and still be able to get the values like this: storage[1][1][1]
As I get it I'm forced to pass all the 121 arrays you can se below to be able to access all dimensions in the array.
My array is built up like this:
storage = new Array();
for (var i1=1;i1<12;i1++){
storage[i1] = new Array();
for (var i2=1;i2<12;i2++){
storage[i1][i2] = new Array();
}
}
Without using a library like jQuery, you can convert your array to JSON, pass it via a URL and decode it on the target page. Converting it to JSON would look like:
var json_string = JSON.stringify(your_array);
Then pass it in a URL:
var your_url = "http://www.your_website.com/page.html?json_string=" + json_string;
And you could decode it back to an array like so:
var your_new_array = JSON.parse(getUrlVars()["json_string"]);
For some more reading, check out this JSON page: http://www.json.org/js.html
JSON.stringify() is supported by all major browsers. Send it to the server via a POST, then have your php retrieve the variable from $_POST and send it back.
As far as I can see there are two main ways to do what you want:
Pass the array to the webserver, and have it send it back on next request.
Store the data locally in the browser.
The first way could get pretty complicated. You would have to store the data in a database, file or cookie/session.
The second way would be the easiest. Use javascript to store the array in the browser. You can either use a cookie, or use the localStorage object.
Using a cookie would require you to serialize the data manually. It would also get passed to the server, so if you want to save bandwidth, you would want to avoid this.
The localStorage method would only store the data locally, and you also don't need to serialize anything, the browser takes care of this for you.
See the links below for more examples.
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp

Is there something similar to sessionStorage but with multidimensional keys?

I'd like to save off values of a tree-like structure locally, then retrieve them based on user interaction. After some research, I found that sessionStorage (or localStorage) might be a good way to go about doing this. But I'm having trouble saving nested data.
Normally you have:
sessionStorage['key'] = 'someString';
I tried to implement something like:
sessionStorage['key1'] = [];
sessionStorage['key1']['key2'] = 'someString';
but I got an undefined error.
I've checked out few other storage libraries, but they only offer that single key-value pair option. Is there anything I'm missing?
Use JSON to serialise the nested data into a string, then decode it when you need to access it as an object...
var nested = {some:{nested:'object'}}
var asJson = JSON.stringify(nested)
sessionStorage['data'] = asJson
var asObject = JSON.parse(sessionStorage['data'])
From developer.mozilla.com:
The DOM Storage mechanism is a means through which string key/value
pairs can be securely stored and later retrieved for use.
Hence I think you cannot store array/dictionary directly in session storage. I highly suggest you that check this link out:
https://developer.mozilla.org/en-US/docs/DOM/Storage

Dynamically Add JS to an ASP.NET page and get results from the JS

Here's my issue:
Client(s) give me separate JS files which will run a check of some sort on the user's system (Browser type, are cookies enabled?, etc.) and a list of acceptable values to be returned from this check.
I want to run through each JS file when a user visits the site and compare the results to the list of acceptable values, then alert the user if they pass these requirements or not.
I'm currently using RegisterClientScriptBlock() to add the JS to the client's page, so it's being run, but I'm having issues getting the result value from the JS back to ASP.NET in order to do the comparison.
I've tried using hidden fields that the JS will dump the value to and ASP.NET will read from, but I'm having difficulty generating the hidden fields on demand (since I have no idea how many Js files the client could have) and have them work in the ASP.NET code.
Any help, or suggestions in the right direction would be awesome, thanks!
What I would do is have the results be an array of KeyValuePair objects that you would then serialize to JSON. So you create the javascript object type like so:
function KeyValuePair(key, value){
this.Key = key;
this.Value = value;
}
Then you would build up an array of KeyValuePairs like so:
//This array is declared in the global scope
var ValueArray = new Array();
function someFunction(){
//this assumes that the key and value variables are created earlier in the function
var valueToStore = new KeyValuePair(key, value);
ValueArray[ValueArray.length] = valueToStore;
}
So at the point when you are done with all your checks you would use the json2 serializer to serialize the array to json for storage in your hidden field.
var jsonToSaveToHiddenField = JSON.stringify(ValueArray);
//Logic to store resulting json and trigger the serverside evaluation here
On the server side you would use JavascriptSerializer to deserialize your json to an array of KeyValuePairs. Here is the msdn doc on that: JavaScriptSerializer Class Reference
So with this approach you only need one hidden field. So you don't need to dynamically create it which should simplify the server side retrieval quite a bit.
The above should work with minimal changes however I haven't run this through a compiler so there might be some minor syntax errors preset.

Categories