GeorgeD GeorgeD - 1 month ago 10
TypeScript Question

Typescript Angular 2 Http post to C# MVC

Trying to pass a payload via Typescript service to an http.post

My .ts code:

saveEdits(body: Object): Observable<Animal[]> {
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post(this.UrlToEdit, body, options)
.map((res: Response) => res.json())
.catch((error: any) => console.log("Edited value did not been saved"));
}


Mention that

private UrlToEdit = '/Home/Edit';


Although the value is up to the service, C# controller not seems to fire up.. An here its code:

[HttpPost]
public async Task<Boolean> Edit([Bind(Include = "animalID,animalName,animalHabitat,animalClass")] Animal animal)
{
if (ModelState.IsValid)
{
db.Entry(animal).State = EntityState.Modified;
await db.SaveChangesAsync();
return true;
}
return false;
}

Answer

I dont know how your whole site is working but maybe this helps you:

First i see an error in your code, you should pass the bodyString in the post not the body

return this.http.post(this.UrlToEdit, bodyString, options)
    .map((res: Response) => res.json())
    .catch((error: any) => console.log("Edited value did not been saved"));

Second post returns an Observable so the post is executed when something subscribes to the observable like this

//...somewhere in your code ...
service.saveEdits(body).subscribe((animals: Animal[]) => console.log(animals));

Also open chrome debugger (or whatever browser you use) and see in the network tab if the post is executed and if there is any error

I hope this helps you

Comments