【问题标题】:Getting Null value in post request in ASP.NET Core 3 from Angular 10从 Angular 10 在 ASP.NET Core 3 的 post 请求中获取 Null 值
【发布时间】:2021-10-27 05:41:34
【问题描述】:

我是 Angular 的初学者,我有一个 City 模型类,其中包含 IdCounty 模型类的列表。如果我摆脱这个列表,我会正确地从 Angular 获取数据,但是如果我发送包含 formArray 列表的 City 对象,在我的 ASP.NET Core Web API 中,我只会得到 city 对象的空值.

这是我的City 模型类:

public class city
{
    [BsonId]
    [BsonIgnoreIfDefault]
    [BsonRepresentation(BsonType.ObjectId)]
    public string id { get; set; }

    public string name { get; set; }

    public Dictionary<string, string> countyId { get; set; }
}

这是发布请求:

[HttpPost]
public async Task<ActionResult> Insert( [FromBody] city city)
{
    // city.countyId.Add("6120e3450d20ad758e4efbaf") ;
    if (ModelState.IsValid)
    {
        await _repository.InsertOneAsync(city);
        return NoContent();
    }
    else
    {
        return BadRequest();
    }
}

这是我的 Angular 组件:

import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import {CityService} from '../city.service';
import {CityDTO} from '../city.model';
import { PerosonnageDTO } from 'src/app/personnage.model';
import { County } from 'src/app/Counties/county.model';
import {  FormArray } from '@angular/forms';
@Component({
  selector: 'app-city',
  templateUrl: './city.component.html',
  styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit {
  form:FormGroup;
  counties:County[];
  cities:CityDTO[];
  
  count:string[];
  city:CityDTO;
  
  constructor(private fb:FormBuilder,private router:Router,private cityservice:CityService) {
  }
  
  @Input()
  model :CityDTO;

  ngOnInit(): void {
    this.cityservice.getAllCounties().subscribe(
      perso =>{
        console.log(perso);
       this.counties = perso ;
      }
    );
    
    this.form = this.fb.group({
      name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
     
      countyId: this.fb.array([this.addcountyGroup()])
    });
  }

  addcountyGroup() {
    return this.fb.group({
      id:[]
    });
  }
   
  get CountyArray()
  {
    return <FormArray>this.form.get('countyId');
  }

  addmcounty()
  {
    this.CountyArray.push(this.addcountyGroup());
  }

  removecounty(index)
  {
    return this.CountyArray.removeAt(index);
  }
  
  submit() {
    // this.model.countyId = this.count;
    //console.log(this.model);

    this.cityservice.create(this.form.value).subscribe(res => {
         console.log('city created successfully!');
         console.log(this.form.value)
         this.router.navigateByUrl('/Home');
    })
  }

  changeClient(value) {
    console.log(value);
  }

  getErrorMessage() {
    const field = this.form.get('name');

    if (field.hasError('required')) {
      return 'the Name field is required';
    }

    if (field.hasError('minlength')) {
      return 'the minimum length is 3';
    }

    return '';
  }
}

这是我的 Angular 表单:

<form (ngSubmit)="submit()" [formGroup]="form">
    <mat-form-field appearance="outline">
      <mat-label>Name</mat-label>
      <input formControlName="name" matInput />
    </mat-form-field>
    
    <ng-container formArrayName="countyId">
      <ng-container *ngFor="let group of CountyArray.controls; let i =index;" [formGroupName]="i">
       <div [formGroup]="group">
         <mat-form-field >
           <mat-select placeholder="Counties*" #clientValue  (selectionChange)="changeClient($event.value)" formControlName="id">
           <mat-option  *ngFor="let client of counties" [value]="client.id" name="id" ngDefaultControl>
             {{client.name}}
           </mat-option>
         </mat-select>
       </mat-form-field>
      </div>
     </ng-container>
    </ng-container>

      <button type="button" (click)="addmcounty()">Add</button>
      <button type="button" (click)="removecounty()">Remove</button>
    <div>
<button mat-flat-button color="primary" type="button" (click)="submit()"  [disabled]="form.invalid">Save Change</button>
<a mat-stroked-button routerLink="/Home">Cancel</a>
    </div>
  </form>

【问题讨论】:

  • 请发布您的 cityservice (create) 方法的代码。

标签: angular mongodb asp.net-core asp.net-web-api


【解决方案1】:

经过几分钟的验证,我发现必须先转换数组,然后才能将其发送到 Web API。

formarray 是一个对象数组,但我必须发送一个字符串数组 所以我用事件处理程序手动重建了字符串数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2021-09-12
    • 1970-01-01
    • 2019-11-01
    • 2021-06-20
    • 2012-07-05
    • 2020-03-30
    相关资源
    最近更新 更多