here is my angular2 Code
addHero(name: string): Promise<Hero> {
let body = JSON.stringify({ name: name });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this._heroUrlPost, name, options)
.toPromise()
.then(res => <Hero>res.json().data)
.catch(this.handleError);
}
And in MVC Controller My Action Method is as follows:
[HttpPost]
public JsonResult PostHeroes([FromBody]string name)
{
//var name1 = Request.Form["name"].ToString();
if (!string.IsNullOrEmpty(name))
{
var hero1 = new Heroes()
{
HeroName = name
};
_dbContext.Hero.Add(hero1);
_dbContext.SaveChanges();
return Json(new { data = hero1 });
}
return Json(new { data="Not Saved"});
}
I always get null.If I use complex Type i get the property being null.Whatever in simple case like this How to make it right? Update:
return this.http.post(this._heroUrlPost, body, options)
.toPromise()
.then(res => <Hero>res.json())
.catch(this.handleError);