Prakash Gupta
Prakash Gupta

Reputation: 213

Angular2 Post request parameter handling in C#

Angular 2 Code Request URl: http://loacalhost:8800/MyController/SaveBookings

let data = {
    occupationListStr: occupations,
    rOccupationListStr: roccsStr,
};
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('MyController/SaveBookings', JSON.stringify(data),options)
    .then(res => {  
        return res.json()
    })
    .catch(this.handleError);

C# code

Controller

Issue: Request.QueryString values occupationListStr and rOccupationListStr are null

public ActionResult SaveBookings()
{
    dynamic occupationListStr = Request.QueryString["occupationListStr"];
    dynamic rOccupationListStr = Request.QueryString["rOccupationListStr"];

    <....Do something.....>

    return <return something>;
}

Upvotes: 0

Views: 954

Answers (2)

Roman
Roman

Reputation: 12171

In your question you send data as Json (using JSON.stringify(data)) in request body but in your action you expect data from query string.

You should either parse Json in your action to some model:

// you can use your own model (some class to parse Json to) instead of "dynamic"
[HttpPost]
public ActionResult SaveBookings([FromBody]dynamic data) 
{
    var occupationListStr = data.occupationListStr;
    var rOccupationListStr = data.rOccupationListStr;

    <....Do something.....>

    return <return something>;
}

OR

you should change your request in Angular 2:

this.http.post('MyController/SaveBookings?occupationListStr=' + occupations + '&rOccupationListStr=' + roccsStr, null, options)
    .then(res => {  
        return res.json()
    })
    .catch(this.handleError);

Upvotes: 1

Habeeb
Habeeb

Reputation: 1040

  1. You dont need to stringify
  2. Create a class in backend (say Occupation) with occupationListStr, rOccupationListStr properties
  3. From the class you can automatically create controller with scaffolding. If you dont want

[httpPost] public IHttpActionResult Post([FromBody]Occupation objOccupation) { }

Upvotes: 1

Related Questions