I am trying to set up a small ASP.NET Web API projects so I can post data to the database from a small React.JS project. I tried alot of sollutions but the results made no sense and I have no idea how to fix it anymore.
I have this very simple model:
public class Hour { public int WeekID { get; set; } } And this is my controller
[HttpPost] public IHttpActionResult AddHour(Hour hour) { return Ok(); } This is the method that I use to POST my data
export const SaveWeek = weekData=> { const headers = new Headers(); headers.append("Content-Type", "application/json"); const Week= { method: "POST", headers, mode: "cors", body: weekData }; console.log("Hours:"); // Returns {"WeekID": 1} console.log(Hours.body); return axios.post("http://localhost:52350/api/REST/AddHour", { Week }); }; The way I call this SaveWeek method in React is:
// The JSON parameter is for testing hard coded to: {"WeekID": 1} handleSave = async json => { const data = await SaveWeek(json); console.log(data); this.closeModal(); }; I know that the axios POST request works, the way I tested that is by changing the method to not use any parameters and looking at the result that where received:
[HttpPost] public IHttpActionResult AddHour(Hour hour) { // This returns a string in which the data that I sent // can be found. string body = Request.Content.ReadAsStringAsync().Result; return Ok(); } The weird thing is that the body will be filled with data when the method does not contain any parameters, but when I provide the method with the Hour object parameter the body will be an empty string (""). And also the Hour object parameter wont be filled with the values that I provide it.
What am I doing wrong here?
SaveWeekmethod in js?public class Model..yet the method signature isHour hour. What does yourHourclass look like?