我正在创建一个 react javascript 组件,它从用户那里收集信息并使用 ajax 将发布请求发送到 url 端点。我的组件正在到达终点。这是举例说明我的问题的代码:
C# 端点 - Controller :
[EnhancedRequireHttps]
[HttpPost]
public ActionResult MyMethod(MyObject myObject)
{...}
我期待的对象:
public class MyObject
{
public string Name;
public string Number;
public long Id;
public int Code;
}
JavaScript 数据:
this.props.newValues = {
Name : "John",
Number : "1234567890",
Id : "1234",
Code : 1
}
javascript ajax请求:
$.ajax({
type: "POST",
url: this.props.endpointurl, // Contains the endpoint
data: this.props.newValues,
success: function(response) {
}.bind(this),
error: function(err) {
}.bind(this)
});
以前,我将所有参数作为我的 MyMethod 的输入,如下所示:
[EnhancedRequireHttps]
[HttpPost]
public ActionResult MyMethod(string Name, string Number, long Id, int Code)
{...}
帖子工作正常,但我试图编写一个干净的代码,所以我创建了一个类来包含这些属性,当我这样做时,我的问题开始了。
我尝试创建一个名为 myObject 的对象以在 js 代码中包含我的参数。 我还尝试使用 $(this.props.newValues).serialize() 或 JSON.stringify(this.props.newValues),以及 dataType = "json"或 contentType = "application/json"。
感谢阅读和帮助,我来这里是为了澄清对我的情况的任何疑问。 :)
最佳答案
您需要指定 contentType 并将 json 作为字符串发送。查看评论:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8", // Try to add this
url: this.props.endpointurl,
data: JSON.stringify(this.props.newValues), // And this
success: function(response) {
}.bind(this),
error: function(err) {
}.bind(this)
});
关于javascript - 当从 javascript 接收到 ajax post 请求时, Controller 得到一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573691/