Jan Trindal
Jan Trindal

Reputation: 219

Empty body when posting data using fetch()

Here is my controller which is getting called, but value is always ends up null:

 public void Post([FromBody]string value) {
 }

This is how it's being called:

function () {
    var data = {
        'sku': $('#radioProduct').val(),
        'qty': $('#productQty').val()
    }
    return fetch('/api/Default', {
         method: 'post',
         headers: {
              'content-type': 'application/json'
         },
         body: JSON.stringify(data)
         }).then(function (res) {
             return res.json();
         }).then(function (data) {
             return data.orderID; // Use the same key name for order ID on the client and server
         });
   }
});

Am I doing anything wrong here? The API does get called but the body is empty.

Upvotes: 1

Views: 479

Answers (1)

John H
John H

Reputation: 14655

It's null because you're POSTing the following JSON:

{
    "sku": "sku's value",
    "qty": 1
}

but your controller is expecting a string. By the fact you've specified application/json as the Content-Type, what you need to do instead is have a class that models the two values you're expecting to receive:

public class ProductInfo
{
    public string Sku { get; set; }
    public int Qty { get; set; }
}

Without doing that, the model binder doesn't know how to associate the values for sku and qty to anything, and so you get null.

Finally, change your action to:

public void Post([FromBody]ProductInfo productInfo)

Model binding is handled entirely by convention, which means associating property names, or primitive values, with JSON or other data you send to a controller.

Upvotes: 1

Related Questions