首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从Angular 10获取ASP.NET核心3中的post请求中的空值

从Angular 10获取ASP.NET核心3中的post请求中的空值
EN

Stack Overflow用户
提问于 2021-08-27 09:03:35
回答 1查看 61关注 0票数 0

我是Angular的初学者,我有一个City模型类,其中包含County模型类的Id列表。如果我去掉这个列表,我可以正确地从Angular获取数据,但是如果我发送包含formArray列表的City对象,在我的ASP.NET Core Web API中,除了city对象,我什么也得不到。

这是我的City模型类:

代码语言:javascript
复制
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; }
}

这是post请求:

代码语言:javascript
复制
[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组件:

代码语言:javascript
复制
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 '';
  }
}

这是我的角度形式:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2021-09-12 12:13:53

经过几分钟的验证后,我发现在将数组发送到web API之前,我必须对数组进行强制转换。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68950762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档