【问题标题】:Model Binding ajax request in .Net Core.Net Core 中的模型绑定 ajax 请求
【发布时间】: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 属性。

Screen

我做错了什么?

请求查询字符串是这样的: {?Id=1&amp;Name=Piotr&amp;Friends%5B0%5D%5BId%5D=1&amp;Friends%5B0%5D%5BName%5D=John&amp;Friends%5B1%5D%5BId%5D=2&amp;Friends%5B1%5D%5BName%5D=Mike}

【问题讨论】:

  • 为什么要用 HttpGet。试试 HttpPost。
  • 当我将其更改为发布所有 Person p 属性为 null 或 0 时;。

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


【解决方案1】:

你需要做几件事才能让它发挥作用。

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 Core[FromBody] 属性配置正确的输入格式化程序以解析发送的 obj。如果是 JSON,ASPNET Core 将使用 Json.NET 库配置输入格式化程序。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多