CodeMan03
CodeMan03

Reputation: 226

How to directly map an object class from angular 2 to to web api using JSON?

I have a model class I created in angular 2 to track fields. This same class also exists as a model in my webapi project.

export class People {
    Name: string;
    Phone: string;
    Date: date;}

export class Address {
 street: string,
 zip: string,
}

in my service I send this to my webapi controller

getPeopleData(peopleModel: People, addressmodel: Address)
{
let headers = new headers(...)
data = {
   "p": peopleModel,
   "a": addressModel
}
let body = JSON.stringify(data);

return this.http.post(url, body, {headers: headers})
.map((response: Response)=> ...
}

finally in my controller

public JArray GetPeopleData([FromBody]JObject models)
{
   var modelPeople = models["p"].ToObject<People>();
   var modelAddress = models["a"].ToObject<Address>();

}

modelPeople and modeAddress doesn't map. How can I get my model to map directly.

All I get are a bunch of null fields when there is a string of data in the JObject.

EDIT: I created a container class that holds the objects of People and Address

public class Container
{
   public People people {get; set;}
   public Address addresss {get; set;}
}

I then passed in the object to the Container and my results are still null

 public JArray GetPeopleData([FromBody]Container container)
    {
       var modelPeople = container.people;
       var modelAddress = container.address;

    }

both have all values of null.

I dont get it I feel like I am so close but something is missing

Upvotes: 0

Views: 979

Answers (1)

Abel Valdez
Abel Valdez

Reputation: 2408

Hello it works for me

//This is a Gobal object
 result = {
    modelPeople: '',
    modelAddress: ''
 }

constructor( private _http: Http ) {

}
getJsonModel() {
    promise = await this._http.get(URL).toPromise().then(
                res => {
                    this.result= res.json();
                }
    );
}

Upvotes: 1

Related Questions