Javascript 控制器mvc中的AJAX post数据为空

Javascript 控制器mvc中的AJAX post数据为空,javascript,jquery,ajax,asp.net-mvc,json,Javascript,Jquery,Ajax,Asp.net Mvc,Json,我尝试将JSON对象发送回服务器。这是我的AJAX调用: $.ajax({ url: '/Home/NewService', async: false, type: "POST", data: JSON.stringify(props), error: function (jqXHR, textStatus, errorThrown) { console.log("FAIL: " + errorThrown); }, suc

我尝试将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时,它显示为空

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

根据,默认内容类型为
application/x-www-form-urlencoded
。如果要将数据作为JSON发送,必须将其更改为

$.ajax({
url:“/Home/NewService”,
contentType:'应用程序/json',
...
});

我认为您无法以您尝试的方式绑定到动态类型。您可以尝试创建映射数据的类,例如:

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!");
    }
});

使用以下代码解决此问题

Ajax调用

我的控制器动作方法


这个5岁的孩子已经有了一个被普遍接受的答案。你能在你的答案中添加一些文字来解释这在被接受的答案上有什么改进吗?我没有太多时间,但这是正确的工作,只需使用这个
       function SaveDate() {
        var obj = {};
        obj.ID = '10';
        obj.Name = 'Shafiullah';

        $.ajax({
            url: '/Home/GetData',
            dataType: "json",
            type: "Post",
            contentType: 'application/json',
            data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
            async: true,
            processData: false,
            cache: false,
            success: function (data) {
                alert(data.id + ' , ' + data.name);
            },
            error: function (xhr) {
                alert('error');
            }
        });
    }
        [HttpPost]
        public IActionResult GetData([FromBody] Employee employee)
        {
            return Json(employee);
        }