[英]How to send a list of objects to controller via Ajax using asp net core 3.1?
I am trying to send a list of objects to controller using ajax and asp .net core.我正在尝试使用 ajax 和 asp .net 核心将对象列表发送到 controller。 My issue is very very simple and there are lots of answers in SO about my issue but none of them solved my issue.
我的问题非常简单,SO 中有很多关于我的问题的答案,但没有一个能解决我的问题。 I am new at ASP.NET CORE but very experienced at ASP.NET( the normal one).
我是 ASP.NET CORE 的新手,但在 ASP.NET(普通)方面非常有经验。
When debbuging I get a null
list of object.调试时,我得到 object 的
null
列表。
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);
在
console.log(detalleVenta);
code I get this:代码我得到这个:
but when hitting parameters controller, I get this:但是当达到参数 controller 时,我得到了这个:
Here are my C# code:这是我的 C# 代码:
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.参数
Venta venta
捕获了良好的参数,但列表detalle
没有。 What am I doing wrong?我究竟做错了什么?
EDIT: tried public JsonResult GuardarVenta(Binderr[] detalle, Venta venta
got same results, list is null in the controller.编辑:尝试
public JsonResult GuardarVenta(Binderr[] detalle, Venta venta
得到了相同的结果,列表是 controller 中的 null。
Usually the easiest way is to pass the array to the backend in the form of Json
.通常最简单的方法是以
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]
):控制器(
Add [FromBody]
):
[HttpPost]
public JsonResult GuardarVenta([FromBody]List<Binderr> detalle)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.