I am working on an Asp.net core 2.1 project and have the below model
Person
public class Person
{
[Key]
public int ID { get; set; }
[Required]
[MaxLength(150)]
public string Name { get; set; }
[Required]
[MaxLength(150)]
public string Family { get; set; }
[Required]
public int Age { get; set; }
}
There is a web API controller in my project that you can see it.
Web API Controller
[Produces("application/json")]
[Route("api/People")]
public class PeopleController : ControllerBase
{
private readonly ApplicationContext _db;
public PeopleController(ApplicationContext db)
{
_db = db;
}
[HttpGet]
public IEnumerable<Person> GetPerson()
{
return _db.Person;
}
}
Now I want to get data from my web API controller and show in index.cshtml
Index.cshtml
<h2>List Person</h2>
<table class="table table-bordered" id="list">
<tr>
<th>ID</th>
<th>Name</th>
<th>Family</th>
<th>Age</th>
</tr>
</table>
<script>
$.getJSON("/api/People", function(res) {
$.each(res, function(key, val) {
alert(val.Age);
var item =
"<tr><td>" +
val.ID +
"</td><td>" +
val.Name +
"</td><td>" +
val.Family +
"</td><td>" +
val.Age +
"</td><td></td></tr>";
$("#list").append(item);
});
});
</script>
Actual Json in Network Tab in browser
[{"id":1,"name":"jack","family":"bfd","age":30},{"id":2,"name":"mr john","family":"sobhany","age":36}]
But there is a problem. All data shows in my view but all values are undefined
.
What is wrong in my codes?
As you can see looking at the JSON, your JSON serializer is converting your C#-oriented names like Name
(note: first letter capitalized) to JavaScript-oriented ones like name
(note: first letter in lower case):
[{"id":1,"name":"jack","family":"bfd","age":30},{"id":2,"name":"mr john","family":"sobhany","age":36}] Note ----^^^^^^
JavaScript is a case-sensitive language, so naturally val.Name
is undefined
because there's no Name
property on val
; you want val.name
instead (and so on for id
, family
, bfd
, age
...).