Florin Pilca
Florin Pilca

Reputation: 160

AJAX post data is null in controller mvc

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

$.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

"[{"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 json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.

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

Upvotes: 6

Views: 26319

Answers (3)

Shafiullah Kawsar
Shafiullah Kawsar

Reputation: 9

Use the following code to solve this problem

Ajax Call

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

Upvotes: -3

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

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:

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

Upvotes: 21

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

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

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

Upvotes: 9

Related Questions