Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX post data is null in c# web api controller

I am sending data to a c# web api controller by using the following call.

$.ajax({
    type: "POST",
    url: "menuApi/menu/Cost",
    data: JSON.stringify(order),
    contentType: "application/json",
    success: function (data) { window.alert('done')},
    dataType: 'json'
});

The c# controller on server side is like this:

public string Cost([FromBody] string order)
{
    var sOrder = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(order);

    return "";
}

The order object in Javascript is a complex object with nested arrays and properties. I am getting data as null. I am not sure how can I get the order sent through the ajax call.

Edit: This is my order object

var order = {
    name:"",
    id:"",
    cost:"",
    details: {
        sItem:[{name:"",cost:""}], 
        dItem:[{name:"",cost:"", components:[{name:"",quantity:""}]}]
    }
}
like image 567
Novice Avatar asked Jun 01 '26 21:06

Novice


1 Answers

Got it, you need to post the ajax request as form data with empty parameter/form field name like this:

    var order = {
        name: "",
        id: "",
        cost: "",
        details: {
            sItem: [{ name: "", cost: "" }],
            dItem: [{ name: "", cost: "", components: [{ name: "", quantity: "" }] }]
        }
    };
    $.ajax({
        type: "POST",
        url: "api/Values",
        data: {'': JSON.stringify(order)} ,
        success: function (data) { window.alert('done') },            
    });
like image 153
michalh Avatar answered Jun 03 '26 11:06

michalh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!