簡體   English   中英

從Angular 7將對象從Array發布到.NET Core 2 API

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

我一直在努力嘗試將數據從數組發布到.net core 2 API。 用戶有一個帶有復選框的網格,每次檢查時,它會將行添加到數組中。 但是,當我嘗試發布數據時,后端的數據為null。 我過去使用反應式表單成功地向api發送了帖子,但是那是當用戶僅填寫一組值時,我需要發送不帶表單的預填充數據對象。

.NET API控制器:

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

角分量:

 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}`);

}

發送填充數組到api:

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

角服務:

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

您應該修改服務器參數以在從angular發送數組時接受數組。 請嘗試將接受的參數更改為

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

可以使用JSON解析嗎?

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

然后您使用Newtonsoft JSON庫獲取數組

BillingMode[] updated = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BillingMode[]>("your body").ToArray();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM