繁体   English   中英

控制器mvc中的AJAX发布数据为空

[英]AJAX post data is null in controller mvc

我尝试将JSON对象发送回服务器。 这是我的AJAX电话:

$.ajax({
    url: '/Home/NewService',
    async: false,
    type: "POST",
    data: JSON.stringify(props),
    error: function (jqXHR, textStatus, errorThrown) {
        console.log("FAIL: " + errorThrown);
    },
    success: function (data, textStatus, jqXHR) {
        console.log("SUCCES");
    }
});

浏览器调试器中对JSON.stringify(props)的评估是

"[{"name":"firstName","value":"firstValue"}]"

这是被调用的控制器中的方法:

[HttpPost]
public void NewService(dynamic json)
{
    Response.Write(json);
}

我遇到的问题是,上面的json变量总是一个空对象。 success函数被调用,但是当我调试时, json var显示为空。

请告诉我我做错了什么。 谢谢。

我认为你不能像你想要的那样绑定到动态类型。 您可以尝试创建一个映射数据的类,例如:

public class Content
{
    public string Name { get; set; }
    public string Value { get; set; }
}

现在你的行动:

[HttpPost]
public ActionResult NewService(Content[] data)
{
    // sweet !
}

在你的js像Olaf Dietsche说你需要指定你的contentType

var props = [
    { "Name": "firstName", "Value": "firstValue" }, 
    { "Name": "secondName", "Value": "secondValue" }
];

$.ajax({
    url: '/Home/NewService',
    contentType: "application/json",
    async: true,
    type: "POST",
    data: JSON.stringify(props),
    error: function (jqXHR, textStatus, errorThrown) {
        console.log("FAIL: " + errorThrown);
    },
    success: function (data, textStatus, jqXHR) {
        console.log("SUCCESS!");
    }
});

根据jQuery.ajax() ,默认内容类型是application/x-www-form-urlencoded 如果要将数据作为JSON发送,则必须将其更改为

$.ajax({
    url: '/Home/NewService',
    contentType: 'application/json',
    ...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM