我试图使用Frombody属性将一个简单对象的数组发布到我的MVC核心控制器,但由于某种原因它会变为null。如果我只发布一个对象,它的工作正常就是我的代码:
$(document).ready(function() {
var tk = new Array();
$("#calendar").fullCalendar({
header: {
left: 'prevYear,prev,next,nextYear',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
defaultView: 'month',
editable: true,
alldayslot: false,
selectable: true,
slotminutes: 15,
nextDayThreshold: "00:00:00",
events: "/Home/FullCalendar",
eventDrop: function(event, delta, revertFunc)
{
Update(event);
},
});
function Update(event) {
var datarow =
{
"id": event.id,
"start": event.start,
"end": event.end,
}
tk.push(datarow);
debugger;
confirm(("Save changes?"))
console.log(JSON.stringify(datarow));
$.ajax({
type: "post",
dataType: 'json',
cache: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(tk),
url: '@Url.Action("JSON", "Home")',
success: function (data) {
debugger;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
debugger;
}
});
}
});
我的控制器类
[HttpPost]
public IActionResult UpdateTask([FromBody] List<Task_fullcal> td)
{
// Do something
// td is always null if passed as an array
//td working fine if passed as single value
}
答案 0 :(得分:0)
在您的操作中删除FromBody,对于复杂类型,Request将在Request主体中包含复杂类型。 尝试使用PostMan并尝试不同的选项。
在URL中传递1个对象,使用[FromUri]
2传递正文中的对象,删除FromBody
3传递像string这样的简单值,如果你想从URL访问
,请使用[FromUri]4传递Request body中的字符串之类的简单值,使用[FromBody]
答案 1 :(得分:0)
我遇到了同样的问题,花了几个小时才弄清楚。我在
中编写了解决方案以下:
我正在.Net Core 3.1中工作,这对我有用:
1。控制器
尝试使用 [FromForm] 代替 [FromBody]
[HttpPost]
public ActionResult CreateOrdersPOSTObject([FromForm] List<T_POS_ENT_ORDER_DETIALS_Temp> prm)
{
//your logic...
return Json(new { msg = "Successfully added " });
}
2。 AJAX通话
不应使用 JSON.stringfy()或 contentType 。
var DATA = [];
DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});
$.ajax({
url: '@Url.Content("~/home/CreateOrdersPOSTObject")',
data: { "prm": DATA },
type: "POST",
dataType: "json",
async: true
});
或者,如果您愿意,可以使用速记 $。post 获得相同的结果
var DATA = [];
DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});
$.post(
'@Url.Content("~/home/CreateOrdersPOSTObject")',
{ "prm": DATA },
function () {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
答案 2 :(得分:0)
就我而言,我在视图中将其转换为JSON字符串:
var seatsJson = JSON.stringify(seats);
然后,在动作中,我使用Newtonsoft将其转换为对象数组:
var seats = JsonConvert.DeserializeObject<SeatsModel[]>(seatsjson);