【发布时间】: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