不确定我哪里出错了,我有一个对象不会发布到我的 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/