0

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>;
}
Muhammed Shevil KP
  • 1,404
  • 1
  • 16
  • 21
Prakash Gupta
  • 203
  • 1
  • 4
  • 13
  • 2
    You are not sending those values as query parameters, you are actually parsing them in a string and sending it on the request body. – Matias Cicero Feb 06 '17 at 13:04
  • Take a look at this http://stackoverflow.com/a/41533506/1876572 – Eldho Feb 06 '17 at 13:15
  • If you go down the route of query strings, once you have changed the Angular Code, I'd suggest changing the method signature to `public ActionResult SaveBookingsPost([FromQuery]string occupationListStr, [FromQuery]string rOccupationListStr)` – peval27 Feb 06 '17 at 13:17

2 Answers2

1
  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) { }

Habeeb
  • 1,020
  • 16
  • 35
1

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);
Roman
  • 11,966
  • 10
  • 38
  • 47