I am trying to fetch selected value from angular select control to an Asp.net Core 3.0 WebApi. when i debugged i found that, the selected value is in string format, but my data model accept integer. I am getting following error
The JSON value could not be converted to System.Int32. Path: $.bankID | LineNumber: 0 | BytePositionInLine: 77.
is there a simple way to cast the string value from select control to integer.
Angular code
Component.ts
export class BankAccountComponent implements OnInit {
constructor(private fb: FormBuilder, private bankService: BankService,
private service: BankAccountService) { }
bankAccountForms: FormArray = this.fb.array([]);
bankList = [];
ngOnInit() {
this.bankService.getBankList()
.subscribe( res => this.bankList = res as []);
this.addBankAccountForm();
this.service.getBankAccountList().subscribe(
res => {
if (res == []) {
this.addBankAccountForm();
}
else {
// generate formarray as per the data received from BankAccont table
(res as []).forEach((bankAccount: any) => {
this.bankAccountForms.push(this.fb.group({
bankAccountID: [bankAccount.bankAccountID],
accountNumber: [bankAccount.accountNumber, Validators.required],
accountHolder: [bankAccount.accountHolder, Validators.required],
bankID: [bankAccount.bankID, Validators.min(1)],
IFSC: [bankAccount.ifsc, Validators.required]
}));
});
}
}
);
}
addBankAccountForm(){
this.bankAccountForms.push(this.fb.group({
bankAccountID: [0],
accountNumber: ['', Validators.required],
accountHolder: ['', Validators.required],
bankID: [0, Validators.min(1)], // here we are using drop down
IFSC: ['', Validators.required],
}));
}
recordSubmit(fg: FormGroup) {
(fg.value.bankAccountID == 0)
this.service.postBankAccount(fg.value).subscribe(
(res: any) => {
fg.patchValue({ bankAccountID: res.bankAccountID });
//this.showNotification('insert');
});
}
}
public class BankAccount
{
[Key]
public int BankAccountID { get; set; }
[MaxLength(20)]
[Required]
public string AccountNumber { get; set; }
[MaxLength(100)]
[Required]
public string AccountHolder { get; set; }
[Required]
public int BankID { get; set; }
[MaxLength(20)]
[Required]
public string IFSC { get; set; }
}
WebApi Controller
[HttpPost]
public async Task<ActionResult<BankAccount>> PostBankAccount(BankAccount bankAccount)
{
_context.BankAccounts.Add(bankAccount);
await _context.SaveChangesAsync();
return CreatedAtAction("GetBankAccount", new { id = bankAccount.BankAccountID }, bankAccount);
}
解决方案
If I correctly understand what you want to do I have the 2 solutions for that
change the value to number when you will send the data to the server
recordSubmit(fg: FormGroup) {
if (fg.value.bankAccountID == 0) {
fg.value.bankID = +fg.value.bankID; // the + operator will change the type to number
this.service.postBankAccount(fg.value).subscribe(
(res: any) => {
fg.patchValue({ bankAccountID: res.bankAccountID });
//this.showNotification('insert');
});
}
}
change the value to number when the select value will be changed
in html