【问题标题】:Controller is geting an empty object when receiving ajax post request from javascript控制器从 javascript 接收 ajax 发布请求时得到一个空对象
【发布时间】:2015-12-10 23:30:32
【问题描述】:

我正在创建一个 react javascript 组件,该组件从用户那里收集信息并使用 ajax 将发布请求发送到 url 端点。我的组件正在到达终点。这是说明我的问题的代码:

C# 端点 - 控制器:

[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"。

感谢您的阅读和帮助,我来这里是为了消除对我的情况的任何疑问。 :)

【问题讨论】:

  • 在控制台调用 JSON.stringify(this.props.newValues) 会产生正确的 JSON,例如像这样:"{"Name":"John","Number":"1234567890","Id":"1234","Code":1}"
  • 我尝试使用这种方法,知道默认的 binder 会处理 JSON 收入,但我的请求在控制器上是空的
  • 您在喜欢的浏览器的网络工具中看到了什么?你能看到正在发送的有效载荷吗?如果是这样,请尝试使用邮递员手动发送有效负载,以查看问题是否出在服务器端:chrome.google.com/webstore/detail/postman/…
  • @DavidGilbertson 正在发送有效负载:Name: John Number:1234567890 Id:1234 Code:1 但控制器正在接收一个空对象。使用邮递员也会发生同样的事情
  • 好吧,只是澄清一下,对象是空的:long 和 int 类型接收 0(默认值)和字符串 null(再次,默认值)

标签: javascript c# ajax post reactjs


【解决方案1】:

您需要指定 contentType 并将 json 作为字符串发送。见 cmets:

$.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)
});

【讨论】:

  • 我为我的疑问添加了一些编辑信息,但我现在正在尝试你的代码,没有使用“charset = utf-8”
  • 嗯,这很尴尬,但我不确定您的解决方案是否有效,因为我在使用您的设置时遇到了 CORS 问题。任何线索为什么?我尝试添加: 到我的端点应用程序配置和我还在我的 ajax 调用中添加了 xhrFields : {withCredentials: true}。
  • 抱歉,不知道 CORS。
  • 无论如何感谢您的帮助,我认为我需要做一点语法调整来清除所有内容。正如我所说,我在 MyObject 类之前就已经使用它了。
  • 如果使用$.post(),则无需设置contentType:api.jquery.com/jquery.post。如果您将对象传递给 data,它将为您更正字符串化 JSON。
猜你喜欢
  • 2017-03-22
  • 2015-09-18
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2017-04-20
相关资源
最近更新 更多