Click here to Skip to main content
16,022,069 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 code I use is:

JavaScript
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.

What I have tried:

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

I appreciate anyone who can suggest how to solve it.
Posted

Taking recommendations that I have read 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.

JavaScript
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"
              if (check) {
                  calificacion = "CUMPLE";
              }

              lista_conceptos.push({
                  movNumero: 0,  //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) {
             }
          })
 
Share this answer
 
The fact that you're using HttpPostedFileBase suggests that you're using .NET Framework and MVC5.

The MVC5 model binder doesn't support deserializing JSON data from form submissions. You would either need to change your parameter type to string instead of List<EntidadDetalleTransaccion>, or change your JavaScript code to serialize the data in the expected format:

ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries - Scott Hanselman's Blog[^]
 
Share this answer
 
Comments
Member 12760369 4-Oct-24 14:53pm    
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)

// Split the string into substrings
char delimiter = ',';
string[] substrings = listaconceptos.Split(delimiter);

// Convert array to list
List<entidaddetalletransaccion> myList = new List<entidaddetalletransaccion>(substrings);
Richard Deeming 7-Oct-24 3:20am    
Because you're trying to pass an array of strings representing the values to the List<T> constructor, which is expecting an int representing the capacity of the new list.

You can't just call random methods and expect them to magically work out what you want them to do. You need to read the documentation to see what the method actually does, and then find a way to fit them together to do what you want.

In this case, you'd need to find a way to parse the sub-strings into instances of your EntidadDetalleTransaccion class, and then add those instances to your list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900