角度选择值字符串解析为整数 [英] Angular select value string parsing to integer

查看:229
本文介绍了角度选择值字符串解析为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从角度选择控件中获取选定的值到Asp.net Core 3.0 WebApi.当我调试时,我发现所选的值是字符串格式,但是我的数据模型接受整数.我收到以下错误

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

无法将JSON值转换为System.Int32.路径:$.bankID |行号:0 |BytePositionInLine:77.

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.

角度代码

Component.ts

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

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

service.ts

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

Component.tsWebApi代码
Webapi/模型

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控制器

[HttpPost]
    public async Task<ActionResult<BankAccount>> PostBankAccount(BankAccount bankAccount)
    {

        _context.BankAccounts.Add(bankAccount);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetBankAccount", new { id = bankAccount.BankAccountID }, bankAccount);
    }

推荐答案

如果我正确理解了您要做什么,我将为您提供2种解决方案

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

  1. 将数据发送到服务器时,将值更改为number

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. 将选择值更改时将值更改为数字在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>

以ts

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

这篇关于角度选择值字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆