Home > Mobile >  The returned list from ajax is empty but the size of the array is correct
The returned list from ajax is empty but the size of the array is correct

Time:10-20

I'm trying to pass a List from the controller to an ajax function, which I need to show a modal carousel images.

The function start when I click on a image, send a value to the ajax function, the ajax function calls a C# method in the controller, and in return I expect to have a List of paths of the images I'm showing.

This is the Html where the function starts:

<div >
      <img  src="@pd.getImagenes()" onclick="GetImagenes(@pd.getNumeroEntrega())" data-img-mostrar="@cont" />
</div>

This is the ajax function:

function GetImagenes(entrega){
    var i = 0;
    console.log(entrega);
    $.ajax({
        method: "GET",
        url: "GetPedidoImagenes",
        contentType: "aplication/json; Charset=utf-8",
        data: { 'entrega': entrega },        
        async: true,
        success: function (result) {
            console.log("Longitud: "   result.length);            
            if (result == 0) {
                alert("No hay Imagenes");
            }
            else {
                while (i < result.length) {
                    console.log(result.count);
                    var carusel = document.getElementById("Entrega_"   entrega);
                    if (i == 0) {
                        var div = document.createElement('div');
                        div.setAttribute('class', 'carousel-item active');
                        var img = document.createElement("img");
                        img.setAttribute('class', 'd-block w-100');
                        div.appendChild(img);
                        img.setAttribute('src', "/imgAndroid/"   result[i].Path);
                        carusel.appendChild(div);
                        i  ;
                    }
                    else {
                        var div = document.createElement('div');
                        div.setAttribute('class', 'carousel-item');
                        var img = document.createElement('img');
                        img.setAttribute('class', 'd-block w-100');
                        div.appendChild(img);
                        img.setAttribute('src', "/imgAndroid/"    result[i].Path);
                        carusel.appendChild(div);
                        i  ;
                    }
                }
     
            }
        }
    })
};

And this is the C# Controller method:

 [HttpGet]
 public List<PedidoViewModel> GetPedidoImagenes(string entrega)
 {
            string consulta;
            List<PedidoViewModel> listaPedidos = new List<PedidoViewModel>();
            MySqlConnection connection = null;
            try
            {
                consulta = "SELECT Path from Entrega WHERE Entrega = '"   entrega   "'";
                using (connection = new MySqlConnection("datasource="   server   ";database="   database   ";"   ";username="   user   ";password="   password   ";"))
                {
                    MySqlCommand cmd = new MySqlCommand(consulta, connection);
                    connection.Open();

                    var reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        PedidoViewModel pedido = new PedidoViewModel();
                        pedido.setPathImagen(reader["Path"].ToString());
                        listaPedidos.Add(pedido);
                    }
                }
                return listaPedidos;

            }catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
}

This is PedidoViewModel:

[Keyless]
    public class PedidoViewModel{
      private string pathIamgenes;

      public PedidoViewModel(){
        pathIamgenes = "";
      }

     public string getImagenes() { return pathIamgenes; }
     public void setPathImagen(string x) { pathIamgenes = x; }
    }

As you can see, I pass a value from the view to the ajax function, and then from the ajax to the controller, and in return I have a list with tha paths, but the array (which is called result) is empty, but has the right size.

What do I mean with the "right size"? If there are 2 images, result has 2 places, or 2 size. How I checked this? with a console.log(result):

(2) [{…}, {…}]
0:{}
1:{}

But as you can see, the array is empty, and I'm expecting to have the paths of the images.

Where I am wrong? I been working for days with this and I can't find a solution.

I'm new with Javascript and ajax, I don't have lot of knowledge, but I think that what I'm doing is not wrong at all.

Edit

I created a public string path{get; set;} in PedidoViewModel and now console.log(result) comes like this:

(2) [{…}, {…}]
0:{path: null}
1:{path: null}

new PedidoViewModel:

[Keyless]
 public class PedidoViewModel{
     public string path{get; set;} = "";
  }

CodePudding user response:

This class doesn't have any serializable properties:

public class PedidoViewModel{
  private string pathIamgenes;

  public PedidoViewModel(){
    pathIamgenes = "";
  }

  public string getImagenes() { return pathIamgenes; }
  public void setPathImagen(string x) { pathIamgenes = x; }
}

It has a field and has methods for interacting with that field. But in general serializers are looking for properties. (As are ORMs, etc. Properties are the standard in C#.)

Refactor your class to use properties, which significantly simplies it anyway:

public class PedidoViewModel{
  public string PathIamgenes { get; set; } = "";
}

Then that one property would be serialized in the JSON:

{
  "PathIamgenes": ""
}

Naturally, the rest of the code which uses this class would need to be adjusted to make use of its new structure.

  • Related