模型在.Net Core中绑定ajax请求

时间:2017-07-20 13:08:15

标签: javascript c# ajax asp.net-core-mvc

在我的项目中,我正在制作这样的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 = ""
        });
    }

问题是请求是触发测试操作结果但是有空白的Freiends列表。数据未绑定到Person类的Friends属性。

Screen

我做错了什么?

请求查询字符串是这样的: {?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}

2 个答案:

答案 0 :(得分:0)

你能试试吗..

$.ajax({
    type: 'post',
    dataType: 'json',
    url: '/Home/Test',
    data: obj
});

服务器端..

[HttpPost]
public IActionResult Test(Person p)

答案 1 :(得分:0)

你需要做一些事情才能让它发挥作用。

<强>的Javascript

    $(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",
        dataType: "application/json",
        type: 'POST',
        url: '/Home/Test',
        //convert your data to a JSON object before you send it
        data: JSON.stringify( obj)
    });

});

ASPNET核心[FromBody]属性配置正确的输入格式化程序来解析发送的obj。对于JSON,ASPNET Core将使用Json.NET库配置输入格式化程序。

[HttpPost]
public IActionResult Test([FromBody]Person p)
{

    return Json(new
    {
        sEcho = "",
        iTotalRecords = 2,
        iTotalDisplayRecords = 2,
        aaData = ""
    });
}