javascript - .NET Core javascript 到 Controller POST

标签 javascript c# asp.net-core

不确定我哪里出错了,我有一个对象不会发布到我的 Controller 。

型号:

public class PostJsonModel
{
    public List<JsonModel> Things { get; set; }
}

public class JsonModel
{
    public int Id { get; set; }
    public string Tests { get; set; }
    public string MoreTests { get; set; }
}

Controller :

    [HttpPost]
    public async Task<IActionResult> DoSomething(PostJsonModel test)
    {
        //Save to the database

        return Json("Success");
    }

JavaScript:

    var test = {
        "Id": 5,
        "Tests": "Testing",
        "MoreTests": "More More More"
    };

    var more = [];

    more.push(test);
    more.push(test);
    more.push(test);

    var allSaveElements = {
        "Things": more
    };

    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/DoSomething', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function () {
        if (xhr.status === 200) {
           //Do something
        }
        else {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send(allSaveElements);

当我闯入 Controller 时,PostJsonModel 的“Things”计数为 0。 查看 chrome 中的网络输出,allSaveElements 正是我所期望的。

这在 .NET Framework (4.7) 应用程序中工作得很好,但由于某些原因在 .NET Core (2.2) 中不行

我显然遗漏了什么,有人可以指出吗?

最佳答案

您要绑定(bind)到一个复杂的对象,并从主体传递数据,在这种情况下,您需要使用 FromBody。

This works perfectly fine in a .NET Framework (4.7) application, but for some reason not in .NET Core (2.2)

你是对的,大约一年前我在过渡到 .NET Core 2.1 时就注意到了这一点。在 .NET Framework 中,如果您只为复杂对象发送一个参数,则不需要使用 FromBody,但在 .NET Core 中,您需要使用它

您可能想看看 Microsoft 提供的以下链接:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2

引用同一个链接

If the default behavior doesn't give the right results, you can use one of the following attributes to specify the source to use for any given target.

[FromQuery] - Gets values from the query string.

[FromRoute] - Gets values from route data.

[FromForm] - Gets values from posted form fields.

[FromBody] - Gets values from the request body.

[FromHeader] - Gets values from HTTP headers.

关于javascript - .NET Core javascript 到 Controller POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678490/

相关文章:

javascript - 如何恢复 Tab 键的正常功能并遍历所有表单输入?

C# MemberwiseClone 不起作用

c# - 类型为 'System.NullReferenceException' 的第一次机会异常发生在 Unknown Module-mvc custom authentication

asp.net-core - 如何使用 ASP.Net Core 3、SPA 应用程序对无效的 api 请求返回错误

c# - 原始 SQL 查询和 Entity Framework Core

asp.net-web-api - Swagger 使用自定义 swagger.json 文件 aspnet core

javascript - JS 过滤器 item[key] 是什么?

javascript - 根据滚动位置更改 div 内容

javascript - JavaScript if 语句的更简洁方法

c# - 从代码创建 Dot Net Nuke 用户