0

I have created dotnet core Web API of CRUD operations, I tested it with postman and works fine, Then I implemented an angular form interface to get the data and passes it to the web API. But I noticed that I am getting a record with null values, after that the web API won't work even with postman. Works only when I delete the null record created by angular.

This is the method class:

export class AddCustomerComponent implements OnInit {

  addCustomerForm: FormGroup;

  constructor(private service: CustomerService, private fb: FormBuilder, private router: Router) {}

  ngOnInit(): void {
    
    this.addCustomerForm = this.fb.group({
      
  VersionId : [null, Validators.required],

  Name : [null, Validators.required],

  Url : [null, Validators.required],

  Dns : [null, Validators.required],

    })
  }
  onSubmit(){
    this.service.addCustomer(this.addCustomerForm.value).subscribe(data => {
      this.router.navigate(["/customers"]);
    })
  }

}

.Net Core API Controller

[HttpPost("AddCustomer")]
        public IActionResult AddCustomer([FromBody]Customer customer)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);
            using (var context = new HrmapsMasterContext())
            {
                context.Customer.Add(customer);
                context.SaveChanges();
                return Ok();

            }
        }

Form code:

<div class="add-customer">
    <form [formGroup]="addCustomerForm" (ngSubmit)="onSubmit()">
        
        <div class="form-group">
            <label for="versionid" class="required">Id</label>
            <input type="number" class="form-control" id="versionId" formComtrolName="versionId" placeholder="Version Id ">
        </div>
        <div class="form-group">
            <label for="name" class="required">HR Portail</label>
            <input type="text" class="form-control" id="name" formComtrolName="name" placeholder="Url">
        </div>
        <div class="form-group">
            <label for="url" class="required">Job Portail</label>
            <input type="text" class="form-control" id="url" formComtrolName="url" placeholder="Url">
        </div>
        <div class="form-group">
            <label for="dns" class="required">DNS</label>
            <input type="text" class="form-control" id="dns" formComtrolName="dns" placeholder="dns">
        </div>
    
        
    
        <button class="btn btn-success" type="submit">Add</button>
        <button class="btn btn-default" [routerLink]="['/customers']">Cancel</button>
    
    </form>
    </div>

Here's my angular service code:

    export class CustomerService {

    _baseURL: string = "api/customers"

    constructor(private http: HttpClient) { }
    getAllCustomers(){
      return this.http.get<customer[]>(this._baseURL+"/getcustomers");

    }
    addCustomer(Customer: customer){


      const customerForAPI = {

        VersionId: Customer.VersionId,
        Name: Customer.Name,
        Url: Customer.Url,
        Dns: Customer.Dns

      };

      
      const body = JSON.stringify(customerForAPI);
      console.log(body);

      return this.http.post<customer>(this._baseURL +'/addcustomer/', body, { headers });

    }
  }

and here's my web API customer model, please notice that I have used Entityframeworkcore the reverse engineer an existing database

    public partial class Customer
    {
        public Customer()
        {
            Pack = new HashSet<Pack>();
        }
        
        public int Id { get; set; }
        public int? VersionId { get; set; }
        public string Website { get; set; }
        public string Twitter { get; set; }
        public string Map { get; set; }
        public string Fax { get; set; }
        public string Name { get; set; }
        public string Ceoname { get; set; }
        public string Activity { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string City { get; set; }
        public string Url { get; set; }
        public string Locality { get; set; }
        public string Street { get; set; }
        public string Town { get; set; }
        public string ZipCode { get; set; }
        public string ConnectionString { get; set; }
        public string Dns { get; set; }
        public bool? IsActive { get; set; }
        public bool? IsDeleted { get; set; }
        public DateTime? LicenseStartDate { get; set; }
        public DateTime? LicenseEndDate { get; set; }
        public Guid? GuidCustomer { get; set; }

        public virtual AppVersion Version { get; set; }
        public virtual ICollection<Pack> Pack { get; set; }
    }
}

here an XML post request works fine with Postman

 {
    "id": 2078,
    "versionId": null,
    "website": null,
    "twitter": null,
    "map": null,
    "fax": null,
    "name": null,
    "ceoname": null,
    "activity": null,
    "email": null,
    "phone": null,
    "city": null,
    "url": null,
    "locality": null,
    "street": null,
    "town": null,
    "zipCode": null,
    "connectionString": null,
    "dns": null,
    "isActive": false,
    "isDeleted": null,
    "licenseStartDate": null,
    "licenseEndDate": null,
    "guidCustomer": null,
    "version": null,
    "pack": []
}
6
  • Can you show us your angular service code? Method "addCustomer" Commented Mar 30, 2020 at 10:38
  • Are you posting the data in json format and sending the content-type headers in the request to the API. Also are you having suitable validation attributes on your model or write suitable validation checks in your controller. Also debug and see if you are getting the argument as just a new object instead of one with values. Commented Mar 30, 2020 at 10:40
  • @GoranSu yes sure, I have added the angular service code Commented Mar 30, 2020 at 11:17
  • @Saravanan Yes, with postman I send http post request in json format with content-type also have validation attributes on the model to specify required fields. Also if I debug without values it passes null values and redirect me. Commented Mar 30, 2020 at 11:25
  • @AbbassiIHEB, I meant to ask if you are adding the appropriate content-type headers in your script code. Commented Mar 30, 2020 at 11:46

2 Answers 2

1

You could try:

const headers: HttpHeaders = new HttpHeaders()
  .set('Content-Type', 'application/json');

export class CustomerService {
.
.
.
addCustomer(customer: Customer) {
    const customerForAPI = {
      // Here your customerForAPI has to correspond to your C# customer class
      VersionId: customer.versionId,
      Name: customer.name,
      Url: customer.url,
      Dns: customer.dns
    };
    const body = JSON.stringify(customerForAPI);
    console.log(body);
    return this.http.post<Customer>(this._baseURL +'/addcustomer/', body, { headers });
  }
Sign up to request clarification or add additional context in comments.

5 Comments

I have tried your solution but the api keeps receiving null object.{"versionId":null,"name":null,"url":null,"dns":null}
Please post your web api Customer model and your new angular service code Btw, check to see if the console.log(body) contains data
I provided what you suggested and checked the console and found this {"versionId":null,"name":null,"url":null,"dns":null}
I have capitalized the letters, but the problem still occurred, here console message {"VersionId":null,"Name":null,"Url":null,"Dns":null}
You should check your onSubmit() method to see if you pick up the values from the form
0

I have miss spelled formControlName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.