0

I am trying to send some image files, an array and a list with Ajax, but when I read it in the maintainer, it does not pass me the values ​​of the list, the value is null. The program is developed in vs 2022 c# mvc. The code I use is:

                var ImagenSeleccionada1 = $("#fileProducto1")[0].files[0];
                var ImagenSeleccionada2 = $("#fileProducto2")[0].files[0];
                var ImagenSeleccionada3 = $("#fileProducto3")[0].files[0];
                var numero = $("#txtNumero").val();

                var transaccion = {
                    movUser : "@User.Identity.Name",
                    movIdTransaction: "2",
                    movNumero: numero,
                    movEntidad: $("#cbbentidad").val()
                }

                var lista_conceptos = [];

                $("#tabla tbody tr").each(function (index) {
                    var concepto = $(this).find("td").eq(0).html();
                    var check = $(this).find("input").prop('checked');
                    var calificacion ="NO CUMPLE"
                    if (check) {
                        calificacion = "CUMPLE";
                    }
 lista_conceptos.push({
    movNumero: numero,  
    movIdTransaction: 2,
    movConcepto: concepto,
    movCalificacion: calificacion,
     })
 })

console.log(lista_conceptos)

var request = new FormData();
request.append("objeto", JSON.stringify(transaction));
request.append("listaconceptos", JSON.stringify(lista_conceptos));
request.append("archivoImagen1", ImagenSeleccionada1);
request.append("archivoImagen2", ImagenSeleccionada2);
request.append("archivoImagen3", ImagenSeleccionada3);

//SEND TRANSACTION
 jQuery.ajax({
     url: '@Url.Action("RegistrarInspeccion", "Transactions")',
     type: "POST",
     data: request,
     processData: false,
     contentType: false,
     success: function (data) {
                     }
                 });

In the controller, the code I have to receive the data is the following, I have tried several options and the one that is closest is this one, the object variable shows me the arrangement, but the conceptlist list does not contain data, the counter is zero. Before the maintainer call, the list data is seen in the console.log, including the parameter sent in the request.

[HttpPost]
        public async Task<JsonResult> RegistrarInspeccion(string objeto, List<EntidadDetalleTransaccion> listaconceptos, HttpPostedFileBase archivoImagen1, HttpPostedFileBase archivoImagen2, HttpPostedFileBase archivoImagen3)

`

I have tried to send the data without Formdata but I get an error with the images.

I have tried passing the parameter as a string separating the data by commas and then converting the string to the list but it shows me an error message Error (active) CS1503 Argument 1: Cannot convert from 'string[]' to 'int' . The code I make is the following:

public async Task<jsonresult> RegistrarInspeccion(string objeto, string listaconceptos, HttpPostedFileBase archivoImagen1, HttpPostedFileBase archivoImagen2, HttpPostedFileBase archivoImagen3)

char delimiter = ',';
string[] substrings = listaconceptos.Split(delimiter);
List<entidaddetalletransaccion> myList = new 
List<entidaddetalletransaccion>(substrings);

Taking the recommendation I am sending 2 methods. In the first I send the concepts, including the list and in the second I send the images. The first method is sent perfectly and from it I must receive the transaction number which I pass as a parameter to the second method. To do this, I place the transaction number in an input. But I have a problem because when I retrieve the value of the input I do not get the value that I entered, it always gives me zero. The second method runs well and the images are received, but I receive the transaction number variable as zero. The code is the following.

function AdicionarMovimiento() {

    if ($("#cbbentidad").val() == 0 || $("#cbbentidad").val() == null) {
    swal("", "Debe seleccionar una entidad.", "warning");
    return
    }

    EnviarTransaccionOperacion();
    EnviarImagenesenTransaccionOperacion();
}

      function EnviarTransaccionOperacion() {
         var transaction = {
              movConductor: "@User.Identity.Name",
              movIdTransaction: "2",
              movNumero: 0,
              movEntidad: $("#cbbentidad").val()
         }

         var lista_conceptos = [];

          $("#tabla tbody tr").each(function (index) {
              var concepto = $(this).find("td").eq(0).html();
              var check = $(this).find("input").prop('checked');
              var calificacion = "NO CUMPLE"
              //var check = $(this).find('Cumple').prop('checked');
              if (check) {
                  calificacion = "CUMPLE";
              }

              lista_conceptos.push({
                  movNumero: 0,  //ojo se envía pero en el proc almac se actualiza
                  movIdTransaction: 2,
                  movConcepto: concepto,
                  movCalificacion: calificacion
              })
         })

         console.log(lista_conceptos);

         jQuery.ajax({
            url: '@Url.Action("RegistrarInspeccion", "Transactions")',
            type: "POST",
            data: JSON.stringify({ oTransaction: transaction, listaconceptos: lista_conceptos }),
            datatype: "json",
            contentType: "application/json; charset=utf-8",

            success: function (data) {
                console.log(data)
                $("#txtNumero").val(data.numeromovimiento);
                }
            },
        })
      }


      function EnviarImagenesenTransaccionOperacion() {

         var transaction = {
          movConductor: "@User.Identity.Name",
          movIdTransaction: "2",
          movNumero: 0,
          movEntidad: $("#cbbentidad").val()
         }

         var ImagenSeleccionada1 = $("#fileProducto1")[0].files[0];
         var ImagenSeleccionada2 = $("#fileProducto2")[0].files[0];
         var ImagenSeleccionada3 = $("#fileProducto3")[0].files[0];

         var request = new FormData(); 
         request.append("objeto", JSON.stringify(transaction));
         request.append("numeromovimiento", $("#txtNumero").val());
         request.append("archivoImagen1", ImagenSeleccionada1);
         request.append("archivoImagen2", ImagenSeleccionada2);
         request.append("archivoImagen3", ImagenSeleccionada3);

         jQuery.ajax({

             url: '@Url.Action("RegistrarInspeccionImagenes", "Transactions")',
             type: "POST",
             data: request,
             processData: false,
             contentType: false, 
             success: function (data) {
             }
          })

1 Answer 1

0

It seems you have mixed the concept of passing application/json and multipart/form-data

you cannot simply use formDataKey to map to ActionMethod parameter of type array or list when using FormData

/*The recipe*/
//you should not pass an array like this when you use FormData
//you end up re-inventing wheel
request.append("listaconceptos",JSON.stringify(lista_conceptos));
//you should use []
$(lista_conceptos).each(function (i, e) {
    request.append("listaconceptos[]",JSON.stringify(e));
});

ASP.NET mvc action method

[HttpPost]
public JsonResult Index(string id)
{
    var listaconceptos = (from concept in Request.Form["listaconceptos[]"]
                            select System.Text.Json.JsonSerializer.Deserialize<EntidadDetalleTransaccion>(concept))
                            .ToList();

    return Json(new { Count = listaconceptos.Count });
}

JavaScript Code

/*Pizza*/
var lista_conceptos = [];
lista_conceptos.push({
    movNumero: 1,
    movIdTransaction: 2,
    movConcepto: "concepto",
    movCalificacion: "calificacion",
});
lista_conceptos.push({
    movNumero: 2,
    movIdTransaction: 3,
    movConcepto: "concepto2",
    movCalificacion: "calificacion2",
});
console.log(lista_conceptos);

var request = new FormData();
//request.append("listaconceptos",JSON.stringify(lista_conceptos)); 
$(lista_conceptos).each(function (i, e) {
    request.append("listaconceptos[]",JSON.stringify(e));
});

//SEND TRANSACTION
var options = {
    url: '@Url.Action("Index", "Home")',
    type: "POST", // For jQuery < 1.9
    method: 'POST',
    data: request,
    cache: false,
    processData: false,
    contentType: false,
    success: function (data) {
        console.log(data);
    }
}
if (request.fake) {
    // Make sure no text encoding stuff is done by xhr
    options.xhr = function () { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
    options.contentType = "multipart/form-data; boundary=" + request.boundary;
    options.data = request.toString();
}
jQuery.ajax(options);

Create multiple action methods to accept binary file uploads as separate PUT/POST requests
and dont combine DTOs with binary data in the same request.

References:
Can I append an array to 'formdata' in javascript?
Sending multipart/formdata with jQuery.ajax
ASP .NET Core (Net 6) POST Read Array from Form Data

Sign up to request clarification or add additional context in comments.

2 Comments

The problem is with the list listconcepts which receives a null value, the images are received well. The transactiondetail entity is as follows: public class EntidadDetalleTransaccion { public int movNumero { get; set; } public int movIdTransaccion { get; set; } public string movConcepto { get; set; } public string movCalificacion { get; set; } }
that was sarcastic so that you provide more details, see updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.