首页 > 解决方案 > 下拉显示值填充在模式的 id 属性中,而不是 Angular 中的实际 id

问题描述

我已经实现了一个在我的角度应用程序中正确填充的下拉列表,但是当我尝试提交我的表单时,它显示的是模型中的显示文本而不是 Id。可能是什么问题据我所知,我所需要的只是

[(ngModel)]="newJob.customerId

用户界面

<label for="customer">Customer</label>
  <select name="customer" required #customer="ngModel" ngModel placeholder="Please select"   [(ngModel)]="newJob.customerId">
    <option [ngValue]="undefined" selected>Please select</option>
    <option *ngFor="let customer of customers"  >{{customer.name}} </option>
  </select>
  <small *ngIf="customer.invalid">Please select a customer</small>

零件

  public createJob(form: NgForm): void {
    if (form.invalid) {
      alert('form is not valid');
    } else {
      console.log(this.newJob);
      this.jobService.CreateJob(this.newJob).then(() => {
        this.jobService.GetJobs().subscribe(jobs => this.jobs = jobs);
      });
    }
  }

模型

export interface JobModel {
  jobId: number;
  engineer: string;
  customerId: number;
  customerName: string;
  when: Date;
}

更新

Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":400,"statusText":"Bad Request","url":"http://localhost:63235/job","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:63235/job: 400 Bad Request","error":{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|9e7e208d-44c84ff36cde4107.","errors":{"$.customerId":["The JSON value could not be converted to System.Int32. Path: $.customerId | LineNumber: 0 | BytePositionInLine: 50."]}}}

标签: angular

解决方案


您需要在 select 内的每个选项上设置一个值,否则默认为显示值。尝试这个:

<option *ngFor="let customer of customers" [value]="customer.customerId">{{customer.name}} </option>

推荐阅读