我可以将一个对象从Angular2传递给一个MVC5帖子吗?

时间:2016-04-27 13:49:32

标签: typescript angular asp.net-mvc-5

我试图将我的对象从Angular2传递到一个帖子到一个MVC控制器。我希望我可以传递实际的对象,但是当我进入我的控制器时,我的所有属性都显示为null。是否可以传递整个对象?我也试过“UrlSearchParameters”,但它也没有用。

这是我的控制器帖子功能:

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

这是我的客户类型:

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

这是我的Angular2服务:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您尝试以下操作:

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

而不是

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

在您的情况下,我认为您收到以下内容:

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

而不是

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