I'm facing an issue where I am trying to send a JSON string from the client (js) to the server (.NET controller) using AJAX post. However, when the data reaches the controller, the list is empty with a count of 0, which is puzzling me.
- JS Code
btnAddMovie.addEventListener("click", () => {
console.log(datesDict);
var dataToSend = formatDataToSend();
console.log(dataToSend);
console.log(JSON.stringify(dataToSend));
$.ajax({
type: "POST",
url: "SubmitMovieAdd",
data: JSON.stringify(dataToSend),
contentType: "application/json",
success: function (response) {
console.log(response);
},
error: function (request, status, error) {
console.log(request.responseText);
}
});
});
function formatDataToSend() {
var jsonToSend = [];
for (const [key, value] of Object.entries(datesDict)) {
jsonToSend.push({
date: key,
hours: value
});
}
return jsonToSend;
}
In datesDict (dictionary), there are values like this: datesDict = 14/05/2024: ['15:00:00', '12:00:00']
In dataToSend, it looks like this: dataToSend = 0: {date: '14/05/2024', hours: Array(2)}
Final JSON.stringify output => [{"date":"14/05/2024","hours":["15:00:00", "12:00:00"]}]
- Controller
[HttpPost("MyAdminDashBoard/MovieAdd/SubmitMovieAdd")]
public IActionResult SubmitMovieAdd(List<MovieAddJsonAppModel> json)
{
return Content(json.Count().ToString());
}
- Model
public class MovieAddJsonAppModel
{
public string Date { get; set; }
public List<string> Hours { get; set; }
}
Could someone please help me troubleshoot and resolve this issue? Thank you :)