I need some guidance on passing an object from Angular2 to an MVC Controller through a post request. Despite my efforts, all properties of the object appear as null in the controller. Is there a way to pass the entire object successfully? I also attempted using "UrlSearchParameters" without success.
Below is the code for my controller's post function:
[HttpPost]
public JsonResult AddClient(Models.Client client)
{
var cli = new Models.Client();
cli.name = client.name;
cli.npi = client.npi;
cli.dateAdded = DateTime.Now.ToShortDateString();
return Json(cli);
}
Here is the structure of my client type:
export interface Client {
name: string;
npi: number;
dateAdded?: string;
id?: number
}
And here is the Angular2 service I am using:
import {Injectable} from 'angular2/core';
import {Client} from './client';
import {RequestOptions, Http, Response, Headers, URLSearchParams} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ClientService {
constructor(private http: Http) { }
getClients(): Observable<Client[]> {
return this.http.get('/Client/GetClients')
.map(this.extractData);
}
addClient(client: Client): Observable<Client> {
let clientUrl = '/Client/AddClient';
let body = JSON.stringify({ client });
let header = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: header });
return this.http.post(clientUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body || {};
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
Any assistance would be greatly appreciated!