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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20922961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:36:59  来源:igfitidea点击:

AJAX post data is null in controller mvc

javascriptjqueryajaxasp.net-mvcjson

提问by Florin Pilca

I try to send a JSON object back to the server. This is my AJAX call:

我尝试将 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");
    }
});

The evaluation of JSON.stringify(props)in the browser's debugger is

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

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

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

This is the method in the controller which is being called:

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

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

The problem I have is that always the jsonvariable from above is an empty object. The successfunction gets called but when I debug the jsonvar is displayed as empty.

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

Please tell me what I am doing wrong. Thank you.

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

回答by Dimitar Dimitrov

I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:

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

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

Now in your action:

现在在你的行动中:

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

And in your js like Olaf Dietsche said you need to specify your contentType:

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

回答by Olaf Dietsche

According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to

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

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

回答by Shafiullah Kawsar

Use the following code to solve this problem

使用以下代码解决此问题

Ajax Call

Ajax 调用

       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');
            }
        });
    }
       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');
            }
        });
    }

My controller action method

我的控制器动作方法

        [HttpPost]
        public IActionResult GetData([FromBody] Employee employee)
        {
            return Json(employee);
        }
        [HttpPost]
        public IActionResult GetData([FromBody] Employee employee)
        {
            return Json(employee);
        }