[Fixed] The JSON value could not be converted to System.Boolean. Path: $

Issue

I’m trying to send a request from Angular front to asp.net API server.
The form to be submitted is defined as:

export class SaleToUpdate {
    id: number;
    shipped: boolean;
    shipDate: string;
    returned: boolean;
    returnDate: string;
}

markup and code

<mat-grid-tile [colspan] = "2" [rowspan] = "1">
        <mat-form-field>
            <input formControlName="shipDate" matInput placeholder="Ship Date">                                         
         </mat-form-field>                
         <div class="radio-group ml-3">
              <mat-radio-group formControlName="shipped" required (ngModelChange)="shipped">           
                    <mat-radio-button value="false">No</mat-radio-button>
                     <mat-radio-button value="true" class="ml-4">Yes</mat-radio-button>
              </mat-radio-group>
         </div>
</mat-grid-tile>  

The onSubmit() method

onSubmit() {    
   if (this.salesService.saleForm.valid) {
      let sale: SaleToUpdate = this.salesService.saleForm.value;  
      console.log(sale); 

      this.salesService.updateSale(sale.id, sale).subscribe(res => {
         console.log(res);
      }, error => {
        console.log(error);
      });
   } 
}

Therefore, basically, my purpose it to send the form data (SaleToUpdate class) to the backend server.

DTO on server-side

using System;
namespace API.Dtos
{
   public class SaleUpdateDto
   {      
       public int Id { get; set; }          
       public bool Shipped { get; set; }
       public DateTime ShipDate { get; set; }       
       public bool Returned { get; set; }
       public DateTime ReturnDate { get; set; }
   }
}

From the console, I got the error

The JSON value could not be converted to System.Boolean. Path: $.shipped | LineNumber: 0 | BytePositionInLine: 274." when click onSubmit from the client.

I noticed the values for shipped&returned from the form are string datatype rather than boolean datatype

Can anyone please help me out with any possible solutions?

Solution

format your boolean fields from the Class

let sale: SaleToUpdate = this.salesService.saleForm.value;  

sale.shipped = sale.shipped === 'true' ? true: false;
sale.returned = sale.returned === 'true'? true: false;

Leave a Reply

(*) Required, Your email will not be published