我正在研究Asp.net core 2.1项目,并具有以下模型
人员
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; }
}
我的项目中有一个Web API控制器,您可以看到它。
Web API控制器
[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;
}
}
现在,我想从Web API控制器获取数据并显示在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>
浏览器的“网络”标签中的实际Json
[{"id":1,"name":"jack","family":"bfd","age":30},{"id":2,"name":"mr john","family":"sobhany","age":36}]
但是有一个问题。所有数据均显示在我看来,但所有值为undefined
。
我的代码有什么问题?
答案 0 :(得分:3)
正如您看到的JSON所示,您的JSON序列化程序将面向C#的名称(如Name
(注:首字母大写)转换为面向JavaScript的名称(如name
(注:首位)小写字母):
[{"id":1,"name":"jack","family":"bfd","age":30},{"id":2,"name":"mr john","family":"sobhany","age":36}] Note ----^^^^^^
JavaScript是区分大小写的语言,因此val.Name
自然是undefined
,因为Name
上没有val
属性;您需要使用val.name
(对于id
,family
,bfd
,age
...等等)。