Shi*_*kei 9 c# model-binding asp.net-core-mvc asp.net-core
我试图在我的视图中将一个Object数组发布到我的控制器但是params为null我看到只是一个简单的对象我需要将[FromBody]放在我的控制器动作中.
这是我的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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我的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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的行动:
[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }
Run Code Online (Sandbox Code Playgroud)
这是我的班级:
public class ReceiveTime
{
public string openTime { get; set; }
public string closedTime { get; set; }
public string id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏:)
Kir*_*kin 10
而不是使用ReceiveTime[] rt,根据您POST的相同结构对数据建模可能更好.例如,您可以创建一个如下所示的类:
public class MesJours
{
public ReceiveTime[] MonJour { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我不知道MesJours作为一个班级名称是否有意义(我不会说法语),但这个想法仍然很明确 - 你可以随心所欲地命名这个班级.
鉴于此,您可以像这样更新您的控制器:
[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
// Access monJour via mesJours.
var rt = mesJours.MonJour;
}
Run Code Online (Sandbox Code Playgroud)
这将满足ASP.NET MVC Model Binder,并且应该为您提供已发布的数据.这还有一个额外的好处,可以轻松容纳您可能想要POST的任何其他属性.
| 归档时间: |
|
| 查看次数: |
10579 次 |
| 最近记录: |