Object array in ajax with mvc

Asked

Viewed 318 times

2

I have a function that takes the variables from a list, creates the objects, and inserts them into a list of objects. But I need to pass this list to the mvc controller;

Jquery function

$(function() {
jQuery.ajaxSettings.traditional = true;
$("#saveDiffer").on('click',
    function(event) {
        event.preventDefault();
        event.stopPropagation();
        var count = 0;
        var differs = [];
        $('.differ').each(function() {
            var nome = $(this).children('input').val();
            var tipo = $(this).find('li.active').find('span').text();
            var differ = {
                Nome: nome,
                Tipo: tipo
            };
            differs.push(differ);

        });
        console.log(differs);
        $.ajax({
            type: 'POST',
            url: '/Upload/SaveDiffer',
            dataType: 'JSON',
            data: JSON.stringify(differs),
            contentType: 'application/JSON; charset=utf-8',
            success: function(data){
                console.log(data);
            },
            error: function(data) {
                console.log(data)
            }

        });

    });
});

Controller

[HttpPost]
    public ActionResult SaveDiffer(List<AtividadeJsonModel> differs)
    {
        // Código aqui
        return null;
    }

Model

public class AtividadeJsonModel
    {
        public string Nome { get; set; }
        public string Tipo { get; set; }
    }

Edit

I tried to use the [FromBody] in the controller, as some responses suggest, but to no avail, it receives a null.

2 answers

1

Instead:

data: JSON.stringify(differs),

Try it like this:

data: JSON.stringify({ 'differs': differs}),

Example:

var cores = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];

JSON.stringify(cores);

// Retorno: "[{"id":1,"color":"yellow"},{"id":2,"color":"blue"},{"id":3,"color":"red"}]"

JSON.stringify({ 'cores': cores });

// Retorno: "{"cores":[{"id":1,"color":"yellow"},{"id":2,"color":"blue"},{"id":3,"color":"red"}]}"
  • Still differs in controller is set to Count 0

0


I managed to make it work using [FromBody] and linking with another template to do the array.

Important: the 'Modelos' should match the name of the array within the model


JSON would look like this {"Modelos":[{"nome":"Teste Ausencia","tipo":"Ausencia"},{"nome":"Teste Extra","tipo":"Extra"}]}

Post:

$.ajax({
   type: 'POST',
   url: '/Upload/SaveDiffer',
   dataType: 'JSON',
   data: JSON.stringify({ 'Modelos': differs }),
   contentType: 'application/JSON; charset=utf-8',
   success: function(data){
      console.log(data);
   },
   error: function(data) {
      console.log(data)
   }
});

The models:

public class AtividadeJsonModel
{
    public Modelo[] Modelos { get; set; }
}
public class Modelo
{
    public string Nome { get; set; }
    public string Tipo { get; set; }
}

And the controller:

[HttpPost]
    public void SaveDiffer([FromBody]AtividadeJsonModel differ)
    {
        insira o código aqui;
    }    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.