Angular select value string parsing to integer

戏子无情 提交于 2021-01-07 03:45:38

问题


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

Component.html

<form  class="tr" [formGroup] ="fg"
    *ngFor="let fg  of bankAccountForms.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" value="{{item.bankID}}">{{item.bankName}}</option>

    </select>
</div>
<div class="td">
    <input  class="form-control" formControlName="IFSC">
</div>
<div class="td">
    <button class="btn btn-success" [disabled]="fg.invalid">
        <i class="far fa-save fa-lg"></i> 
        Submit</button>
</div>
</form>

service.ts

 postBankAccount(formData) {
    return this.http.post(environment.apiBaseURI + '/BankAccount', formData);
}

Component.ts WebApi code
Webapi/Model

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

回答1:


If I correctly understand what you want to do I have the 2 solutions for that

  1. 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');
        });
   }
}
  1. change the value to number when the select value will be changed in html
    <select #bankIdSelect class="form-control" (change)="onChangeBankId(bankIdSelect.value)">
        <option value="0">Select</option>

        <option *ngFor="let item of bankList" value="{{item.bankID}}">{{item.bankName}}</option>

    </select>

in ts

onChangeBankId(bankId) {
    this.fg.get('bankID').patchValue(+bankId);
}



回答2:


Before sending data to your API convert all number values from string to number by simply adding '+' in front of them.



来源:https://stackoverflow.com/questions/59125976/angular-select-value-string-parsing-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!