Home > Net >  api action POST with complex data receives null
api action POST with complex data receives null

Time:10-05

I have a javascript object that I am sending via ajax to a Asp.net Core (.Net 5) controller. The jquery client looks like this:

$.ajax({
    type: 'POST',
    url: '/api/Product',
    dataType: 'json',
    contentType: 'application/json',
    statusCode: {
        200: ProductDone
    },
    error: 'ProductError',
    data: JSON.stringify(product)
});

Fiddler shows the data being sent as:

 { "productId":"0",
   "ourSKU":"mc11",
   "productName":"mc11",
   "description":"",
   "priceExclTax":"22",
   "priceInclTax":"33",
   "active":"true",
   "vendors": [ { 
       "vendorId":6,
       "theirSKU":"",
       "notes":"",
       "storedPurchaseCost":"11",
       "storedPurchaseCostCurrencyId":0,
       "active":true
   } ]
}

On the server side I have a controller action like this (note the [FromBody]):

[HttpPost("api/[action]")]
public IActionResult Product([FromBody] ProductUploadInfo prod)
{
    return Ok();
}

with the following classes defined:

public class ProductUploadInfo
{
    public int productId { get; set; }
    public string ourSKU { get; set; }
    public string productName { get; set; }
    public string description { get; set; }
    public int taxTypeId { get; set; }
    public decimal priceExclTax { get; set; }
    public decimal priceInclTax { get; set; }
    public bool active { get; set; }
    public List<VendorUploadInfo> vendors { get; set; }

    public ProductUploadInfo()
    {
        vendors = new List<VendorUploadInfo>();
    }
}

public class VendorUploadInfo
{
    int vendorId { get; set; }
    string theirSKU { get; set; }
    string notes { get; set; }
    decimal storedPurchaseCost { get; set; }
    int storedPurchaseCostCurrencyId { get; set; }
    bool active { get; set; }
}

The problem is that when the api action is invoked, the passed-in prod object is absent (null). If I remove the [FromBody], there is a prod object, but it is empty (all strings are null, all integers are 0, and the list has 0 elements).

How do I code the controller api action to receive the data that is being sent by the client?

CodePudding user response:

The binding is failing because you have incompatible data types between the JS object and your C# model. The data being sent from the ajax request are wrong. For example for property public decimal priceExclTax { get; set; } you are passing "priceExclTax": "22" which is a string value. You should be passing "priceExclTax": 22 instead. The data object you pass to JSON.stringify should be like this:

{
  "productId": 0,
  "ourSKU": "mc11",
  "productName": "mc11",
  "description": "",
  "priceExclTax": 22,
  "priceInclTax": 33,
  "active": true,
  "vendors": [{
    "vendorId": 6,
    "theirSKU": "",
    "notes": "",
    "storedPurchaseCost": 11,
    "storedPurchaseCostCurrencyId": 0,
    "active": true
  }]
}
  • Related