【发布时间】:2017-07-20 13:08:15
【问题描述】:
在我的项目中,我正在发出这样的 ajax 请求:
$(document).ready(function () {
var friends = [];
friends[0] = { Id: 1, Name: "John" };
friends[1] = { Id: 2, Name: "Mike" };
var obj = {
Id: 1,
Name: "Piotr",
Friends: friends
}
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'GET',
url: '/Home/Test',
data: obj
});
});
我正在尝试将数据绑定到以下类:
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public IEnumerable<Friend> Friends { get; set; }
}
public class Friend
{
public long Id { get; set; }
public string Name { get; set; }
}
实际效果如下:
[HttpGet]
public IActionResult Test(Person p)
{
HttpRequest r = HttpContext.Request;
return Json(new
{
sEcho = "",
iTotalRecords = 2,
iTotalDisplayRecords = 2,
aaData = ""
});
}
问题是请求正在触发测试操作结果,但好友列表为空白。数据未绑定到 Person 类的 Friends 属性。
我做错了什么?
请求查询字符串是这样的:
{?Id=1&Name=Piotr&Friends%5B0%5D%5BId%5D=1&Friends%5B0%5D%5BName%5D=John&Friends%5B1%5D%5BId%5D=2&Friends%5B1%5D%5BName%5D=Mike}
【问题讨论】:
-
为什么要用 HttpGet。试试 HttpPost。
-
当我将其更改为发布所有 Person p 属性为 null 或 0 时;。
标签: javascript c# ajax asp.net-core-mvc