10 votes

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

I have this function:

    data: procesoData,
    succes: function(datos){ 

where procesoData corresponds to a list of data:

var procesoData = { 'items':[ ] }

My question is How can I work with them (receive the parameter in the form of a list) in a controller of MVC 5 in C#? Any help I would be good, thanks.

Question originally on Google+


Diego Torres Points 5328

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 controller Home2:

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

    return Json(resultado);

Here it depends on the type of items in items, in the simplest case, if a set of strings usuarías List<string>.

Probably you are sending objects with more properties, in that case you'd have to create a class in C# that follow the structure of the objects from JavaScript to MVC deserialize in this. For example, if on the client side you have

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

Then in C# you could create a class

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

and in the signature of the action to use List<Usuario> items

On the other hand, if the object you're sending has more properties than only items it would be advisable to create a specific model to get all

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

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

public ActionResult Test01(ProcesoData data)


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: