Я прочитал много других людей, у которых эта проблема отправлена и массив объектов для кода за C#.Массив объектов (Javascript) на C# через Ajax
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);
Сдвиги необработанных данных
{"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 строк в событиях. Поэтому где-то данные теряются при отправке.
Любая помощь по этому вопросу будет замечательной.
Edit 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);
попробовать: Сдвиги = JSON.stringify (смены); и передавать данные в виде данных: {events: Shifts} в параметре ajax. –
Что такое @AnupamSingh - это распространенная ошибка, которую вы совершили. Вы хотите, чтобы контент был JSON, но ваши ключи все равно должны быть обычными ключами. –
Дал выстрел и все еще получал 0 объектов на стороне C#. - См. Редактировать 1 для изменений – Caz1224