Search code examples
angularangular2-formsangular2-services

How to post boolean value from ng2 service to MVC WebAPI


I am trying to post value from ng2 service to my MVC WebAPI. It works, when the value is false. It doesn't post back when the value is true.

My service.ts

EnrolStudent(HasCriminal: boolean): Observable<number> {

        console.log(HasCriminal);

        return this.http.post('/api/student/enrolstudent', HasCriminal).map(result => {
            return result.json() as number;
        }).catch(error => {
            console.log(error);
            return Observable.throw(new Error('Error occured in calling EnrolStudent service'));
        });

    }

In the above code, I can trace and clearly see that HasCriminal is true/false in the console.

If the value is false, it sends the param correctly. enter image description here

However, if the value is true, it doesn't send out anything even though I can see true, in the console.enter image description here

Could you please suggest me how I could send this boolean value correctly to my MVC Webapi?


Solution

  • For single primitive values you have to use url encoding. Alternatively you can wrap it in an object on the client and on the server side. Assuming you want to keep the server code unchanged here is the modification to the client code needed.

    const options = {
        headers: new Headers({ 'content-type':'application/x-www-form-urlencoded'})
    } as RequestOptionsArgs;
    const data = '=' + HasCriminal.toString();
    
    return this.http.post('/api/student/enrolstudent', data, options).map((result: Response) => {
        return result.json() as number;
    }).catch(error => {
        console.log(error);
        return Observable.throw(new Error('Error occured in calling EnrolStudent service'));
    });