0

Not sure if I have the routing or syntax right as I'm a little new to Angular routing. But the 'isPartial' parameter is always false.

Here is my code in Angular/Typescript where I'm calling my webservice controller. I'm passing an id and a boolean 'isPartial', the id comes in fine but the isPartial is always false

// .ts file
this.webService.add(this.claim.id, true)
  .subscribe(result => {
    // do some stuff
  }, error => {
    // take care of error
  });

// web service 
add(id: number, isPartial: boolean): Observable <any> {
  return this.http.post(this.baseUrl + 'webservice/add/' + id, isPartial);
}

// my route
{
  path: 'claim/:id',
  component: ClaimComponent,
  resolve: {
    claim: ClaimResolver
  },
  canDeactivate: [PreventUnsavedChanges]
},

here is my controller

[Route("api/[controller]")]
[ApiController]
public class WebServiceController : ControllerBase
{
    [HttpPost("add/{id}")]
    public async Task<IActionResult> Add(int id, bool isPartial) 
    {
       // isPartial is always false
    }
}
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • from where you are calling `add` method? can you post the code from where the service is calling `add` method? – Plochie Jan 12 '20 at 06:46

2 Answers2

1

I have configured two possible solutions for your condition.

Solution 1: Set your request Content-Type to application/json instead of the default Content-Type: text/plain;charset=UTF-8

ts:

import { HttpClient, HttpHeaders } from '@angular/common/http';
//...
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
add(id: number, isPartial: boolean): Observable <any> {
    return this.http.post(this.baseUrl + 'webservice/add/' + id, isPartial, httpOptions);
}

controller:

[HttpPost("add/{id}")]
public async Task<IActionResult> Add(int id, [FromBody]bool isPartial)

Solution 2: wrap isPartial in a model,it is recommend if you have multiple parameters.

ts:

add(id: number, isPartial: boolean): Observable <any> {
    return this.http.post(this.baseUrl + 'webservice/add/' + id, { 'isPartial': isPartial });
}

http.post(baseUrl + 'api/SampleData/add/' + id, { 'isPartial': isPartial })

controller:

public class myModel
{
    public bool isPartial { get; set; }
}

[HttpPost("add/{id}")]
public async Task<IActionResult> Add(int id, [FromBody]myModel myModel)
Ryan
  • 19,118
  • 10
  • 37
  • 53
0

change your parameter binding in C# controller like this

[Route("api/[controller]")]
[ApiController]
public class WebServiceController : ControllerBase
{
    [HttpPost("add/{id}")]
    public async Task<IActionResult> Add( [FromUri]int id, [FromBody]bool isPartial) 
    {
       // isPartial is always false
    }
}
divyang4481
  • 1,584
  • 16
  • 32