Send via Json data to the controller

7

I am trying to send via Ajax some data from my form. In this form, I have inputs normal fields and a list of providers that I previously selected through the checkbox. Follow screen:

I'mcreatingtheJSONobjectandsendingitviaAjax,butmylistcomesnullincontroller.

Ajax:

varnomeUsuario=$("#NomeUsuario").val();
            var sobrenomeUsuario = $("#SobrenomeUsuario").val();
            var codigoUsuario = $("#CodigoUsuario").val();
            var emailUsuario = $("#EmailUsuario").val();

            //Busca todos os fornecedores selecionados
            var listCnpj = [];
            $('#datagrid tbody tr').filter(':has(:checkbox:checked)').each(function () {
                var elem = $(this)[0];
                listCnpj.push("Codigocnpj:" + elem.cells[0].innerHTML);
            });

            // build json object
            var squirrel = {
                NomeUsuario: nomeUsuario,
                SobrenomeUsuario: sobrenomeUsuario,
                CodigoUsuario: codigoUsuario,
                EmailUsuario: emailUsuario,
                ListaFornecedorViewModels: [listCnpj]
            };
            $.ajax({
                type: 'POST',
                url: 'Gravar',
                data: squirrel,
                dataType: 'json',
                success: function (data) {

                },
                error: function (data) {

                    alert('Error' + data);
                }
            });

Controller:

    [HttpPost]
    public JsonResult Gravar(UsuarioViewModel usuarioViewModel)
    {
        JsonResult json = new JsonResult();
        return json;

    }

And my model:

public class UsuarioViewModel {

    public int Id { get; set; }
    public string CodigoUsuario { get; set; }
    public string NomeUsuario { get; set; }
    public string SobrenomeUsuario { get; set; }
    public string SenhaUsuario { get; set; }
    public string EmailUsuario { get; set; }
    public int Status { get; set; }
    public string Prontuario { get; set; }
    public string FornecedorBusca { get; set; }
    public List<Fornecedor> ListaFornecedorViewModels { get; set; }

}
    
asked by anonymous 21.09.2015 / 21:09

1 answer

2

I already had this problem, passed the parameter as being string JSON :

In your Ajax use this:

var dataJson = JSON.stringify(squirrel);

 $.ajax({
                type: 'POST',
                url: 'Gravar',
                data: { modelo: dataJson },
                dataType: 'json',
                success: function (data) {

                },
                error: function (data) {

                    alert('Error' + data);
                }
            });

Rename the parameter of your method in the controller to string:

 [HttpPost]
    public JsonResult Gravar(string modelo)
    {
        JsonResult json = new JsonResult();
        return json;
    }

This solution should work.

    
22.09.2015 / 02:07