Required to get a list of objects of class Man

public class Man { public int Id { get; set; } public string Firstname { get; set; } public string Secondname { get; set; } public int Age { get; set; } } 

I send a request to the server

 $.ajax({ url: url, type: "POST", data: { "count": count }, dataType: "json" }) 

In the controller's method, I form an array of objects and send it to the client.

 for (int i = 0; i < dif; i++) { mans[i] = await manContext.Mans.FirstOrDefaultAsync(m => m.Id == mansCount - dif + i); } return Json(mans); 

How can I get the value of the fields of the Man object (name, age, etc.) from JSON using JS?

  • Provide an example of a generated Json server - Digital Core

1 answer 1

Request example:

 $.ajax({ type: "POST", url: url, data: { count: 'count' }, dataType:'json', success: function(data){ alert ( data.Firstname), alert ( data.Age) } }); 

AJAX POST Form Button Event Handling

 <!DOCTYPE html> <html> <head> <title>jQuery AJAX POST</title> <meta charset="utf-8"> </head> <body> <div id="response"> <pre></pre> </div> <form id="my-form"> <button type="submit">Submit</button> </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> (function($){ function processForm( e ){ $.ajax({ url: 'http://ip-api.com/json/', dataType: 'text', type: 'post', contentType: 'application/x-www-form-urlencoded', data: $(this).serialize(), success: function( data, textStatus, jQxhr ){ $('#response pre').html( data ); }, error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); } }); e.preventDefault(); } $('#my-form').submit( processForm ); })(jQuery); </script> </body> </html> 

JSON C # Serialization

 [DataContract] class Man { [DataMember] public int Id { get; set; } [DataMember] public string Firstname { get; set; } [DataMember] public string Secondname { get; set; } [DataMember] public int Age { get; set; } public Man() { } public Man(int Id, string Firstname, int Age) { this.Id = Id; this.Firstname = Firstname; this.Age = Age; } } 

Deserialization Json C #

 DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Man)); Man newitems = (Man)jsonFormatter.ReadObject(File.OpenRead("Man.json")); 

Json javascript

 <script> var user = '{ "Id": 1, "Firstname": "Вася", "Secondname": "Васильев", "Age": 28 }'; user = JSON.parse(user); alert( user.Age ); </script> 

  • You need to deserialize the client to Javascript when receiving a response from the server - ZOOM SMASH
  • @ZOOMSMASH added JavaScript to the response - Digital Core
  • Here you create the user yourself, but I need to get him out of the array that comes from the server in json - ZOOM SMASH
  • @ZOOMSMASH answer to your question: the first sample code, further analysis with examples of use. - Digital Core
  • one
    [{"id": 40, "firstname": "Vasya", "secondname": "Pupkin", "age": 34}] That's what comes back, it turns out you have to turn with a small letter - ZOOM SMASH