Search code examples
.netangularasp.net-core

Posting objects from Array to .NET core 2 API from Angular 7


I've been struggling with trying to post data from an array to a .net core 2 API. the user has a grid with check-boxes and on each check, it adds the row to the array. however when i attempt to post the data, it's coming in null on the back-end. i've made posts to api's successfully in the past using reactive forms, but that was when it was just one set of values filled out by the user, i need to send prefilled data objects without forms.

.NET API Controller :

[HttpPost("api/updateBillingRecords")]
        public async Task<ActionResult<BillingModel[]>> UpdateBillingRecords([FromBody] BillingModel updatedBillingRecords)
        {
            var incomingRecords =  await kiraBillingService.UpdateBillingRecordsAsync(updatedBillingRecords);
            return Ok("RECORDS UPDATED");
        }

Angular Component :

 doNotBill(i) {
  var index = this.doNotBillRecords.indexOf(i);

  if (index === -1) {

    this.doNotBillRecords.push(i);
  } else {

    this.doNotBillRecords.splice(index, 1);
  }


  // test if records are being added and removed accordingly
  console.log(`Dynamic Data: ${this.doNotBillRecords.values}`);

}

Sending filled array to API:

updateBilling() {
    this.billingService.updateBillingRecords(this.doNotBillRecords).subscribe();
  }

Angular Service:

updateBillingRecords(billingRecord): Observable<BillingRecord[]> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.post<BillingRecord[]>(this.updateBillingRecordsAPIUrl, billingRecord, { headers: headers });
  }

Solution

  • you should modify the server parameter to accept an array as you send array from angular . please try to change the parameter accepted to be

     public async Task<ActionResult<BillingModel[]>> UpdateBillingRecords([FromBody] BillingModel[] updatedBillingRecords)