I'm trying to post an array of Object in my view to my controller but params are null i saw that for just a simple object I need to put [FromBody] in my controller action.
Here is my JSON:
{
"monJour": [
{
"openTime": "04:00",
"closedTime": "21:30",
"id": "0"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "1"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "2"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "3"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "4"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "5"
},
{
"openTime": "08:00",
"closedTime": "17:30",
"id": "6"
}
]
}
Here is my Ajax Request :
function SendAllDay() {
var mesJours = {};
var monJour = [];
mesJours.monJour = monJour;
var senddata ='';
$('div[id^="Conteneur"]').each(function () {
var idDiv = $(this).attr("id");
var jour = idDiv.substr(9, idDiv.length - 9);
var opentps = $("#O" + jour).val();
var closetps = $("#C" + jour).val();
var monid = $("#id" + jour).val();
monJour = {
openTime: opentps,
closedTime: closetps,
id: monid
}
mesJours.monJour.push(monJour);
});
$.ajax({
url: '@Url.Action("ReceiveAll")',
dataType: 'json',
type: 'POST',
//data: JSON.stringify(monJours),
data: JSON.stringify(mesJours),
contentType:'application/json',
success: function (response) {
console.log('ok');
//window.location.reload();
},
error: function (response) {
console.log('error');
//alert(response)
//window.location.reload();
}
});
}
Here is my Action:
[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }
Here is my Class:
public class ReceiveTime
{
public string openTime { get; set; }
public string closedTime { get; set; }
public string id { get; set; }
}
Any help is appreciated :)
Instead of using ReceiveTime[] rt
, it might be better to model the data according to the same structure that you POST. For example, you could create a class that looks like this:
public class MesJours
{
public ReceiveTime[] MonJour { get; set; }
}
I don't know if MesJours
makes sense as a class name (I don't speak French), but the idea is still clear - You can name the class whatever you like.
Given this, you could update your controller like this:
[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
// Access monJour via mesJours.
var rt = mesJours.MonJour;
}
This would satisfy the ASP.NET MVC Model Binder and should give you the data you've POSTed. This also has the added benefit of easily accommodating any additional properties you might want to POST.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With