我有一个webapi来获取银行帐户详细信息,当我尝试使用邮递员对其进行测试时,它可以正常工作,但是尝试从我的有角度的客户端访问put方法时,却出现了以下错误。
这是错误
PUT https://localhost:44332/api/bankaccount/null 400
errors:
id: ["The value 'null' is not valid."]
$.bankAccountID: [""The JSON value could not be converted to System.Int32. Path: $.bankAccountID | LineNumber: 0 | BytePositionInLine: 21."]
从错误中可以明显看出,我得到的是空值而不是整数。我无法弄清楚为什么它达到空值,您能帮我这个忙吗?我在Angular 8中使用Asp.net Core 3.0
component.html中的表单代码
<form class="tr" [formGroup]="fg" *ngFor="let fg of bankAccountForm.controls" (submit)="recordSubmit(fg)">
<div class="td">
<input class="form-control" formControlName="accountNumber" >
</div>
<div class="td">
<input class="form-control" formControlName="accountHolder" >
</div>
<div class="td">
<select class="form-control" formControlName="bankID" >
<option value="0">Select</option>
<option *ngFor="let item of bankList" [ngValue]="item.bankID">{{
item.bankName
}}</option>
</select>
</div>
<div class="td">
<input class="form-control" formControlName="IFSC" >
</div>
<div class="td">
<button type="submit" class="btn" [ngClass]="(fg.get('bankAccountID').value==0?'btn-success':'btn-outline-dark')"
[disabled]="fg.invalid"><i class="far fa-save fa-lg"></i>
{{fg.get('bankAccountID').value==0?'Submit':'Update'}}</button>
</div>
</form>
component.ts表单创建
addBankAccountForm(){
this.bankAccountForm.push(this.fb.group({
bankAccountID:[0],
accountNumber:['', Validators.required],
accountHolder:['', Validators.required],
bankID:[0, Validators.min(1)],
IFSC:['']
}));
}
将方法保存在component.ts文件中
if(fg.value.bankAccountID==0)
{
this.service.postBankAccount(fg.value).subscribe(
(res:any) =>{
fg.patchValue({bankAccountID:res.bankAccountID});
});
}
else{
// here if i try to console fg.value i get bankAccountID as null
this.service.putBankAccount(fg.value).subscribe(
(res:any) =>{
});
}
}
在service.ts类中放入方法
putBankAccount(formData){
return this.http.put(environment.apiBaseURI + '/bankaccount/'+ formData.bankAccountID, formData);
}
WebApi模型类
public class BankAccount
{
public int BankAccountId { get; set; }
public string AccountNumber { get; set; }
public string AccountHolder { get; set; }
public int BankID { get; set; }
public string IFSC { get; set; }
}
控制器放置方法
// PUT: api/Banks/5
[HttpPut("{id}")]
public async Task<IActionResult> PutBank(int id, Bank bank)
{
if (id != bank.BankID)
{
return BadRequest();
}
_context.Entry(bank).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BankExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
您是否尝试过将api的“ [FromRoute]”属性添加到“ id”参数中?另外,我强烈建议始终使用“ ===”运算符,而不是JavaScript / TypeScript中的“ ==”运算符