Reputation: 6413
If I have in my db a table called User with name, Id, age fields and I want to get these data and put it in a var as a JSON serialize, then I want to send it to javascript page to reform it as I want . I need to know how to put these data in a var as a JSON, how to read the data in the javascript file (how to deal with each one. for example : array[name]) !!!?
which thing is more better to deal with these data in asp.net code then send it in the javascript or to send it to the javascript and then to deal with !!? thank u :D
Upvotes: 0
Views: 149
Reputation: 129832
If you have an object in .NET you can serialize it using the JavaScriptSerializer
List<User> myUsers = GetAllUsers();
string userJson = new JavaScriptSerializer().Serialize(myUsers);
This way you won't have to worry about escaping quotes or anything. Now that you have a string, you can feed that to your javascript:
var userJson = ... // the JSON string
var myUsers = JSON.parse(userJson);
The other way around, you may have a javascript object, that you want to pass to the server:
var myUsers = ... // a JS object
var userJson = JSON.stringify(myUsers);
If you pass the string userJson
to the server, you can then deserialize it. If you know that the JS object corresponds entirely, in terms of property names, to a .NET object, or an array of .NET objects, say, you can deserialize it as such:
List<User> myUsers = new JavaScriptSerializer().Deserialize<List<User>>(userJson);
If there isn't a .NET object that can be directly mapped to the structure of the JS object, you'll have to use
object myUsers = new JavaScriptSerializer().DeserializeObject(userJson);
Upvotes: 1
Reputation: 643
4guysfromrolla have great articles that will teach you the ins and outs of it.
https://web.archive.org/web/20210927191305/http://www.4guysfromrolla.com/articles/102010-1.aspx
https://web.archive.org/web/20211020203220/https://www.4guysfromrolla.com/articles/040809-1.aspx
you can take a look at these for your complete understanding.
besides if you just want to display results of a query ti the UI then why dont you use the gridview or repeater controls.
Upvotes: 0