我读过很多其他人在将对象数组发送到 C# 背后的代码时遇到的问题。
Javascript
--This constructs an array of objects called Shifts,
-- there is more too it but it is just how it iterates the divs for elements and such,
-- not important for this issue.
-- This is where the issue is, or I suspect in the way the data is sent and retrieved.
Shifts = JSON.stringify({ events: Shifts });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/API/ManRoster',
data: Shifts,
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
console.log(data);
},
type: 'POST'
});
console.log(Shifts);
Shifts Raw Data
{"events":[{"ShiftID":"10","EVTDate":" 2016-04-15","UID":"1","Notes":"hgr"},{"ShiftID":"10","EVTDate":" 2016-04-15","UID":"1","Notes":"hgr"},{"ShiftID":"15","EVTDate":" 2016-04-15","UID":"1","Notes":"uyuy"},{"ShiftID":"15","EVTDate":" 2016-04-15","UID":"1","Notes":"uyuy"}]}
ManRoster.cs
[HttpPost("")]
public JsonResult Post(List<Models.Event> events)
{
try
{
_context.Events.AddRange(events);
return Json(true);
}
catch
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed");
}
}
Event.cs
public class Event
{
[Key]
public int EVTID { get; set; }
public int UID { get; set; }
public int ShiftID { get; set; }
public DateTime EVTDate { get; set; }
public string Notes { get; set; }
}
在 ManRoster.cs 中,我在事件中得到 0 行。因此,数据在发送过程中会丢失。
有关此问题的任何帮助都会很棒。
编辑 1
更改了 JavaScript
Shifts = JSON.stringify(Shifts);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/API/ManRoster',
data: { events: Shifts },
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
console.log(data);
},
type: 'POST'
});
console.log(Shifts);
最佳答案
假设您的预字符串转换类似于:
[
{
"ShiftID": 10,
"EVTDate": "2016-04-15",
"UID": 1,
"Notes": "hgr"
},
{
"ShiftID": 10,
"EVTDate": "2016-04-15",
"UID": 1,
"Notes": "hgr"
},
{
"ShiftID": 15,
"EVTDate": "2016-04-15",
"UID": 1,
"Notes": "uyuy"
},
{
"ShiftID": 15,
"EVTDate": "2016-04-15",
"UID": 1,
"Notes": "uyuy"
}
]
您应该将 [FromBody] 属性添加到参数中,以告诉模型绑定(bind)器该值来自主体:
[HttpPost("")]
public JsonResult Post([FromBody]List<Models.Event> events)
{
try
{
_context.Events.AddRange(events);
return Json(true);
}
catch
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed");
}
}
你的 JavaScript 应该是这样的:
Shifts = JSON.stringify(Shifts);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/API/ManRoster',
data: Shifts,
error: function () {
$('#info').html('<p>An error has occurred</p>');
},
success: function (data) {
console.log(data);
},
type: 'POST'
});
console.log(Shifts);
关于javascript - 通过 Ajax 将对象数组 (Javascript) 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491683/