decoder
decoder

Reputation: 926

Angular2 Http Post to Asp.net 5 Controller Parameter binding get null

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

Upvotes: 2

Views: 1539

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202196

Your code implies that you have a data property in your response payload:

return this.http.post(this._heroUrlPost, body, options)
    .toPromise()
    .then(res => <Hero>res.json().data) // <-----
    .catch(this.handleError);

Something like that:

{
  "data": {
    (...)
  }
}

Is it the case? You should use this rather:

return this.http.post(this._heroUrlPost, body, options)
    .toPromise()
    .then(res => <Hero>res.json()) // <-----
    .catch(this.handleError);

Edit

I think that you need to send a url encoded form instead of JSON data. This can be done like this:

addHero(name: string): Promise<Hero> {
  var params = new URLSearchParams();
  params.set('name', name);

  let body = params.toString();
  let headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'
  });
  let options = new RequestOptions({ headers: headers });
  return this.http.post(this._heroUrlPost, name, options)
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
}

If you need to pass the name as query parameter, use this:

let options = new RequestOptions({ headers: headers, search: params });

Don't forget to import the URLSearchParams class. And controller method public JsonResult PostHeroes(string name)

See this question:

Upvotes: 1

Related Questions