问题
My issue is very very simple but I have not found any solution about this issue in the entire internet. I am new at ASP.NET CORE MVC and I feel its AJAXs is very hard to understand compared to the normal ASP.NET.
Well I am trying to pass an array/list of objects to controller but I cant make this. It is Very simple but it does not work the way I want ( In the normal ASP.NET MVC worked great).
For example I have this:
var detalleVenta = new Array();
$.each($("#tableventa tbody tr"), function () {
detalleVenta.push(
{
"ProductoId" : $(this).find("td").eq(6).html(),
"Cantidad" : $(this).find("td").eq(2).html(),
"Precio" : $(this).find("td").eq(3).html(),
"Total" : $(this).find("td").eq(4).html()
}
);
});
$.ajax({
method:"POST",
data: JSON.stringify(detalleVenta),
"dataType": "json",
"contentType": "application/json",
url: '@Url.Action("GuardarVenta", "Venta")',
traditional: true,
success: function(data, textStatus) {
if (data == "OK" ){
location.href = '@Url.Action("Index","Compra")'
}
}
,
})
MVC controller:
public JsonResult GuardarVenta([FromBody]List<DetalleBinding> detalle)
{
...
}
public class DetalleBinding
{
public string ProductoId {get; set;}
public string Cantidad {get;set;}
public string Precio {get;set;}
public string Total {get;set;}
}
This way worked for me, ajax sends the list successfully data to controller:
But my issue is... what if I want to send more data appart from that data? I Normally write it in JSON format like this : data : { "detalle" : detalleVenta, "Name" : "Mary", "Age" : 34}
but my issue is that this does not work for me.
I tried this:
$.ajax({
method:"POST",
data: {"detalle" : JSON.stringify(detalleVenta)},
"dataType": "json",
"contentType": "application/json",
url: '@Url.Action("GuardarVenta", "Venta")',
traditional: true,
success: function(data, textStatus) {
if (data == "OK" ){
location.href = '@Url.Action("Index","Compra")'
}
}
,
})
But it does not bind to controller and gives me null.
What I am doing wrong?
This is what console.log(JSON.stringify(detalleVenta))
shows:
回答1:
In Doc you can see:
Don't apply [FromBody] to more than one parameter per action method. Once the request stream is read by an input formatter, it's no longer available to be read again for binding other [FromBody] parameters.
So if you want to send more data ,the easiest way is through querystring,like below(change url):
$.ajax({
method:"POST",
data: JSON.stringify(detalleVenta),
dataType: "json",
contentType: "application/json",
url: "Venta/GuardarVenta?age=34&name=Marry",
traditional: true,
success: function(data, textStatus) {
if (data == "OK" ){
location.href = '@Url.Action("Index","Compra")'
}
Action:
public JsonResult GuardarVenta([FromBody]List<DetalleBinding> detalle,int age,string name)
{
...
}
来源:https://stackoverflow.com/questions/65088046/asp-net-core-mvc-ajax-not-working-properly