'Getting "undefined" on response.d MVC ASP.NET Core Ajax
I´m trying to create a datatable using Ajax, but before creating and filling the data table with the ajax response, on success I send an alert with "response.d" it returns undefined and thats why im not filling the data table.
Script
<script>
$(document).ready(function () {
$('#tabHistorialTrabajos').click(function () {
$.ajax({
type: "GET",
url: "/Monitoreo/GetData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
//success: OnSuccess,
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
});
function OnSuccess(response) {
$("datatableTrabajos").DataTable(
{
blengthchange: true,
lengthmenu: [[5, 10, -1], [5, 10, "all"]],
bfilter: true,
bsort: true,
bpaginate: true,
data: response.d,
columns: [{ 'data': 'idTrabajo' },
{ 'data': 'idTurnoXMaquina' },
{ 'data': 'parte' },
{ 'data': 'cliente' },
{ 'data': 'cantidadPedido' },
{ 'data': 'cantidadMerma' },
{ 'data': 'cantidadTarimas' },
{ 'data': 'fechaInicio' },
{ 'data': 'fechaFin' },
{ 'data': 'cantidadFabricado' },
{ 'data': 'tiempoMuerto' },
{ 'data': 'velocidad' },
{ 'data': 'fabricado' }
]
});
};
</script>
Controller (returns a JSON)
public string GetData()
{
ServiciosMenu serviciosMenu = new ServiciosMenu();
List<CorridaModel> listadoTrabajosXMaquina = serviciosMenu.GetHistorialTrabajosXMaquina(4);
string JsonResult = JsonConvert.SerializeObject(listadoTrabajosXMaquina);
return JsonResult;
}
Solution 1:[1]
We need to change the default value of maxJsonLength
. I learned from github that the default value of this maxJsonLength is 30M.
And suggestion for yor method in Controller:
public JsonResult GetData()
{
List<TestPersonModel> list = new List<TestPersonModel>();
TestPersonModel m = null;
for (int i = 0; i < 10; i++)
{
m = new TestPersonModel();
m.name = "John" + i;
m.age = i+1;
m.car = "car" + i;
list.Add(m);
}
return Json(list);
}
public class TestPersonModel {
public string name { get; set; }
public int age { get; set; }
public string car { get; set; }
}
Under normal circumstances, we do not return string
types, but generally return Json
types.
Since the length of the string of your return type is not clear, it is possible that the current problem can be solved by the above code.
If it doesn't work, it is recommended to refer to the link below, or provide the code for the smallest unit that can be reproduced.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jason |