Can I pass an object from Angular2 to an MVC5 Post

2019-07-25 15:06发布

问题:

I am trying to pass my object from Angular2 through a post to an MVC Controller. I was hoping I could pass the actual object in, but all of my properties are appearing as null when it gets into my controller. Is it possible to pass the entire object in? I also tried with "UrlSearchParameters" but it didnt work either.

Here's my controller 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's my client type:

export interface Client {
    name: string;
    npi: number;
    dateAdded?: string;
    id?: number
}

Here's my Angular2 service:

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);
    }
}

Thanks for any help!

回答1:

You try the following:

 addClient(client: Client): Observable<Client> {
    let clientUrl = '/Client/AddClient';
    let body = JSON.stringify(client); // <----------

instead of

addClient(client: Client): Observable<Client> {
    let clientUrl = '/Client/AddClient';
    let body = JSON.stringify({ client });

In your case, I think that you receive the following content:

{
  "client": {
    // client properties
    "name": "some name",
    "npi": "some npi",
    (...)
  }
}

instead of

{
  // client properties
  "name": "some name",
  "npi": "some npi",
  (...)
}