简体   繁体   中英

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:""}]}]
    }
}

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

The model binder's already done it for you, no need for deserializing. You just need to change parameter type to object or dynamic . Thing left is consideration to remove that redundant processing:

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

        return "";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM