lucahuy
lucahuy

Reputation: 800

React POST data to ASP.Net

I'm using the React template when creating a new project in Visual Studio. It has something like this for GET request:

  fetch('api/SampleData/WeatherForecasts')
    .then(response => response.json())
    .then(data => {
      this.setState({ forecasts: data, loading: false });
    });

I'm learning how to do a POST request, so I modified the code to:

  const formData = new FormData();
  formData.append('values', this.state.values);

  fetch('api/SampleData/WeatherForecasts', {
      method: 'POST',
      body: formData
  }).then(response => response.json())

But not sure how to retrieve the formData on ASP.Net:

[HttpPost("[action]")]
public string WeatherForecasts()
{
  // How to print out the values from formData here
  // System.Diagnostics.Debug.WriteLine(Request.Form.ToString());

  return "Hello";
}

Edit: I also don't know how to return a Json result from ASP.Net:

[HttpPost("[action]")]
public JsonResult WeatherForecasts()
{
  // How to print out the values from formData here
  // System.Diagnostics.Debug.WriteLine(Request.Form.ToString());

  // How to return a Json here
  // return {hello: 'Hello'};
}

Upvotes: 0

Views: 2189

Answers (1)

norbitrial
norbitrial

Reputation: 15166

My answer presumes that your this.state.values property contains a string for testing purposes only just like the following:

this.setState({
  values: 'testingtext' 
});

I guess you are on the right track, from front-end side I assume the data is being sent. You can additionally check in the browser's network tab how the data has been passed in the HTTP request's body.

I would modify the WeatherForcecasts() action as the following to capture the data on the back-end side:

[HttpPost]
public string WeatherForecasts([FromBody] string values)
{
  // here you can check what has been passed to the values variable

  return values;
}

About [FromBody] why you need to include into the attribute:

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.

Source: Sending Simple Types

If you want to override the action name in your route then you can achieve that by adding into your method the [ActionName("YOUR_NEW_ACTION_NAME")] attribute but it is not a mandatory one:

You can override the action name by using the [ActionName] attribute.

Source: Routing by Action Name

I hope this helps! I guess this gives you an idea how to proceed further.

Upvotes: 1

Related Questions