Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 415
Florin Pilca Avatar asked Jan 04 '14 15:01

Florin Pilca


2 Answers

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!");
    }
});
like image 146
Dimitar Dimitrov Avatar answered Nov 07 '22 23:11

Dimitar Dimitrov


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',
    ...
});
like image 36
Olaf Dietsche Avatar answered Nov 07 '22 23:11

Olaf Dietsche