简体   繁体   中英

Update record function not updating Angular8 dotnet Core 3 application

I followed a tutorial to create a crud app with angular 8 and dotnet core 3. Everything works except the update supplier detail function. I get a 400 error when trying to update a record.

Any help will be appreciated>

Here is my full project on github: https://github.com/JancoBreiTech/Angular-ApiCRUD-NorthwindDB

Dotnet code snippets: Data Transfer Object: EditSupplierDto


using System;
using System.ComponentModel.DataAnnotations;

namespace AspNetAngular.Dtos
{
    public class EditSupplierDto
    {
        [Required]
        public int SupplierId { get; set; }
        [Required]
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
        public string HomePage { get; set; }
    }
}

SupplierController: PutSuppliers:


  // PUT: api/Supplier/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutSuppliers([FromRoute] int id, [FromBody] EditSupplierDto editSupplierDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != editSupplierDto.SupplierId)
            {
                return BadRequest();
            }

            var preSupplier = _mapper.Map<Suppliers>(editSupplierDto);
            _repo.Update(preSupplier);
            await _repo.SaveAsync(preSupplier);

            return NoContent();
        }

Angular code snippets: api.service.ts

const apiUrl = 'http://localhost:5000/api/supplier';

updateSupplier (id: number, supplier: any): Observable<any> {
    const url = `${apiUrl}/${id}`;
    return this.http.put(url, supplier, httpOptions).pipe(
      tap(_ => console.log(`updated Supplier id=${id}`)),
      catchError(this.handleError<any>('updateSupplier'))
    );
  }

Supplier-Edit.ts


import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from '../api.service';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

@Component({
  selector: 'app-supplier-edit',
  templateUrl: './supplier-edit.component.html',
  styleUrls: ['./supplier-edit.component.sass']
})
export class SupplierEditComponent implements OnInit {
  supplierId : number; //added supID
  supplierForm: FormGroup;

  companyName = '';
  contactName = '';
  contactTitle = '';
  address = '';
  city = '';
  region = '';
  postalCode = '';
  country = '';
  phone = '';
  fax = '';
  homePage = '';
  isLoadingResults = false;
  matcher = new MyErrorStateMatcher();

  constructor(private router: Router, private route: ActivatedRoute, private api: ApiService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.getSupplier(this.route.snapshot.params['id']);
    this.supplierForm = this.formBuilder.group({
      'companyName' : [null, Validators.required],
      'contactName' : [null, null],
      'contactTitle' : [null, null],
      'address' : [null, null],
      'city' : [null, null],
      'region' : [null, null],
      'postalCode' : [null, null],
      'country' : [null, null],
      'phone' : [null, null],
      'fax' : [null, null],
      'homePage' : [null, null]
    });
  }
  getSupplier(id: number) {
    this.api.getSupplier(id).subscribe(data => {
      this.supplierId = data.supplierId;
      this.supplierForm.setValue({
        companyName: data.companyName,
        contactName: data.contactName,
        contactTitle: data.contactTitle,
        address: data.address,
        city: data.city,
        region: data.region,
        postalCode: data.postalCode,
        country: data.country,
        phone: data.phone,
        fax: data.fax,
        homePage: data.homePage
      });
    });
  }
  onFormSubmit(form: NgForm) {
    this.isLoadingResults = true;
    this.api.updateSupplier(this.supplierId, form)
      .subscribe(res => {
          this.isLoadingResults = false;
          this.router.navigate(['/supplier']);
        }, (err) => {
          console.log(err);
          this.isLoadingResults = false;
        }
      );
  }
  supplierDetails() {
    this.router.navigate(['/supplier-details', this.supplierId]);
  }

}

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

In update component you haven't mentioned supplierId property in this.supplierForm form and in PutSuppliers action method you are checking a condition that

if (id != editSupplierDto.SupplierId)
            {
                return BadRequest();
            }

because there is no SupplierId in EditSupplierDto request object it was going for BadRequest().

So please include

ngOnInit() {
    this.getSupplier(this.route.snapshot.params['id']);
    this.supplierForm = this.formBuilder.group({
      'supplierId':[null]  <========================= add this one
      'companyName' : [null, Validators.required],
      'contactName' : [null, null],

and

getSupplier(id: number) {
    this.api.getSupplier(id).subscribe(data => {
      this.supplierId = data.supplierId;
      this.supplierForm.setValue({
        supplierId: data.supplierId  <========================== add this one
        companyName: data.companyName,
        contactName: data.contactName,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM