c# – Send List type parameters by AJAX to a controller in MVC 5

Question:

I have this function:

$.ajax({ 
    type:"post", 
    url:"/Home2/test01", 
    data: procesoData,
    succes: function(datos){ 
        $("#DatosRespuesta").html(datos); 
    }
);

where processData corresponds to a list of data:

var procesoData = { 'items':[ ] }

My question is how can I work with them (receive the parameter as a list) in an MVC 5 controller in C #? Any help would be good for me, thank you.

Question originally asked on Google+

Answer:

MVC performs the binding according to the names of the parameters and the type, then to receive the elements of an array according to the example in your Home2 controller :

[HttpPost]
public ActionResult Test01(List</* tipo de los elementos */> items) {
    var resultado = // Los datos que quieres devolver

    return Json(resultado);
}

Here depends on the type of elements that are in items , in the simplest case if it were a set of user strings List<string> .

You are probably sending objects with more properties, in that case you would have to create a class in C # that follows the structure of JavaScript objects so that MVC deserializes them in it. For example if on the client side you have

var procesoData = { 'items': [ 
    { nombre: 'uno', edad: 1 }, 
    { nombre: 'dos', edad: 2 }, 
    { nombre: 'tres', edad: 3 }
] };

So in C # you could create a class

public class Usuario
{
    public string Nombre { get; set; }
    public int Edad { get; set; }
}

and in the action signature use List<Usuario> items


On the other hand, if the object that is being sent has more properties than just items it would be advisable to create a specific model to receive everything.

public class ProcesoData
{
    public int Id { get; set; }
    public string Descripcion { get; set; }
    public List<Usuario> Items { get; set; }
}

the data would also be automatically mapped by the name of the properties and you would use this model

[HttpPost]
public ActionResult Test01(ProcesoData data)
Scroll to Top