Reputation: 485
I am trying to send a list of objects to controller using ajax and asp .net core. My issue is very very simple and there are lots of answers in SO about my issue but none of them solved my issue. I am new at ASP.NET CORE but very experienced at ASP.NET( the normal one).
When debbuging I get a null
list of object.
This is my code:
var detalleVenta = new Array();
detalleVenta.length = 0;
$.each($("#tableventa tbody tr"), function () {
detalleVenta.push({
ProductoId: $(this).find('td:eq(6)').html(),
});
});
console.log(detalleVenta);
var datos =
{
// ignore this, i am trying to capture other data.
"Nit": document.getElementById('Nit').value,
"Nombres":document.getElementById('nombres').value,
"NoComprobante":document.getElementById('nocomprobante').value,
"ClienteId":document.getElementById('clienteselect').value,
"Direccion":document.getElementById('direccion').value,
"FormaPago":document.getElementById('selectformapago').value,
// This is the list I want to send to controller
"detalle": detalleVenta,
};
$.ajax(
{
url: '/Venta/GuardarVenta/',
method:"POST",
data: datos,
traditional: true,
success: function(data, state) {
location.reload();
return;
},
error: function(xhr, textStatus, txt) {
alert(xhr.responseText);
return;
}
});
In the console.log(detalleVenta);
code I get this:
but when hitting parameters controller, I get this:
Here are my C# code:
public class VentaController : Controller
{
[HttpPost]
public JsonResult GuardarVenta(List<Binderr> detalle, Venta venta)
{
}
}
public class Binderr
{
public string ProductoId {get;set;}
}
The parameter Venta venta
captures good the parameters but the list detalle
does not. What am I doing wrong?
EDIT: tried public JsonResult GuardarVenta(Binderr[] detalle, Venta venta
got same results, list is null in the controller.
Upvotes: 1
Views: 4244
Reputation: 7190
Usually the easiest way is to pass the array to the backend in the form of Json
.
Here is a simple example:
var detalleVenta =
[
{ id: "1" },
{ id: "2" },
{ id: "3" }
]
$.ajax({
"type": "POST",
"url": '/Venta/GuardarVenta/',
"dataType": "json",
"contentType": "application/json",
"data": JSON.stringify(detalleVenta),
})
Controller(Add [FromBody]
):
[HttpPost]
public JsonResult GuardarVenta([FromBody]List<Binderr> detalle)
{
}
Upvotes: 3