I know that this question has been asked several times, but none of the previous solutions helped me out with my problem (that seems a pretty simple one actually). I just want to send a Json object to a Post method that I created in a controller class. Here's the interesting portion of my controller class:
[Route("api/[controller]")]
public class CodeController : Controller
{
[HttpPost]
public void Post([FromBody] InfoNegozio value)
{
return;
}
}
I kept it simple as I just want the value to be set properly. Here's the class InfoNegozio:
public class InfoNegozio
{
public int IdNegozio { get; set; }
public string NomeNegozio { get; set; }
public int AttesaStimata { get; set; }
public DateTime UltimoAggiornamento { get; set; }
}
This is the code used to send data to this API:
var myData = { "IdNegozio": idNegozio, "AttesaStimata": tempoAttesa };
$.ajax({
url: "api/Code",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(myData)
});
The JQuery code just call the webapi controller, the value field is a not null InfoNegozio object, but the field IdNegozio and AttesaStimata are always 0.
I could ask that I'm using a controller in a Razor Page project, and I had to add this line of code in the Startup.Configure method in order to make it work (with "it" I meant the other webapi GET methods).
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
Any Idea?
Edited
Using postman I figured out what the difference is between a wroking call and a not working one. The posting this json with postman is works:
{
"IdNegozio": 1,
"AttesaStimata": 36
}
Unfortunately, with jquery, using JSON.stringify, I get this (note the double quote on the values):
{
"IdNegozio": "1",
"AttesaStimata": "36"
}
And this don't work! Are Json stringify incompatible with .net core Web Api? Is it possible there isn't a clean approach to make those 2 libraries work together?
Edited 2
I ended up building the json manually, forcing jquery to sent "my version", so my js code is now looking:
var myData = '{ "IdNegozio": '+idNegozio+', "AttesaStimata": '+tempoAttesa+' }';
$.ajax({
url: "api/Code",
type: "POST",
contentType: "application/json",
dataType: "json",
data: myData
});
Anyway I don't like this solution as it seems I'm not using the right way to build the json object, so any smarter solution would be much appreciated.