控制器从javascript接收ajax post请求时得到一个空对象
本文关键字:一个 对象 接收 javascript ajax post 请求 控制器 | 更新日期: 2023-09-27 18:12:39
我正在创建一个react javascript组件,该组件收集来自用户的信息,并使用ajax向url端点发送post请求。我的组件到达了端点。下面的代码举例说明了我的问题:
c# endpoint - 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
}
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)
});