我试图将 View 中的对象数组发布到 Controller ,但参数为空,我看到对于一个简单的对象,我需要将[FromBody]放入 Controller Action 中。
这是我的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"
}
]
}
这是我的Ajax请求:
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();
}
});
}
这是我的 Action :
[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }
这是我的课:
public class ReceiveTime
{
public string openTime { get; set; }
public string closedTime { get; set; }
public string id { get; set; }
}
任何帮助表示赞赏:)
最佳答案
与其使用ReceiveTime[] rt
,不如根据POST的相同结构对数据进行建模。例如,您可以创建一个如下所示的类:
public class MesJours
{
public ReceiveTime[] MonJour { get; set; }
}
我不知道
MesJours
作为类名是否有意义(我不会说法语),但想法仍然很明确-您可以随心所欲地命名该类。鉴于此,您可以像这样更新 Controller :
[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
// Access monJour via mesJours.
var rt = mesJours.MonJour;
}
这将满足ASP.NET MVC Model Binder的要求,并应为您提供已发布的数据。这还具有轻松容纳您可能要发布的任何其他属性的额外好处。
关于c# - ASP.NET Core发布数组对象JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47731755/