Why does not the value that I send from the controller to the javascript of the view arrive?

1

I work ASP.NET MVC, Visual Studio 2015, the problem that is happening to me is that when I register a new record it sends me a json, it is more redirecting me showing me the json since my method is a JsonResul, then it does not It's nothing abnormal.

[HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Create(ClienteViewModel entity)
    {
        try
        {
            if (ModelState.IsValid)
            {
                config = new MapperConfiguration(cfg => cfg.CreateMap<ClienteViewModel, Cliente>());
                var cliente = config.CreateMapper().Map<Cliente>(entity);
                clienteService.Create(cliente);
                ModelState.Clear();
            }
            var resultado = new { guardado = true };
            return Json(resultado);
        }
        catch (Exception ex)
        {
            return Json(string.Format("{ success: 'false', message: {0}}", ex.Message));
        }
    }

Ajax code from the view.

function reloadTableClientes() {
    $.ajax({
        url: '@Url.Action("Create", "Cliente")',
        success: function (result) {
            //console.log("Perú esta en el mundial")
            alert("Perú esta en el mundial")
            if (result.guardado) {
                window.clientes.ajax.url('@Url.Action("ListaClientes", "Cliente")');
            }
        }
    });
};

Apparently it is not sending the value of true that it sent from the controller, because if it were that way it would have entered the if.

At no time do I tell the controller that if he registered a record the true take the success.

What I'm trying with that Ajax is to reload datatable.net through this action of the controller.

public JsonResult ListaClientes()
    {
        List<Cliente> _cliente = clienteService.GetAll().ToList();
        config = new MapperConfiguration(cfg => cfg.CreateMap<Cliente, ClienteViewModel>());
        List<ClienteViewModel> list = config.CreateMapper().Map<List<ClienteViewModel>>(_cliente);
        return Json(list, JsonRequestBehavior.AllowGet);
    }

But if you look at the Ajax I try to update the datatable.net which is called my datatable clients.

 window.clientes.ajax.url('@Url.Action("ListaClientes", "Cliente")');

My datatable.net

$(document).ready(function() {
    $("#clientes").DataTable({
        "language": {
            "sProcessing": "Procesando...",
            "sLengthMenu": "Mostrar _MENU_ registros",
            "sZeroRecords": "No se encontraron resultados",
            "sEmptyTable": "Ningún dato disponible en esta tabla",
            "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix": "",
            "sSearch": "Buscar:",
            "sUrl": "",
            "sInfoThousands": ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst": "Primero",
                "sLast": "Último",
                "sNext": "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending": ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        },
        ajax: {
            url: '@Url.Action("ListaClientes", "Cliente")',
    "dataSrc": ''
    },
    columns: [
        { "data": "ClienteId" },
        { "data": "RazonSocial" },
        { "data": "NumeroDocumento" },
        { "data": "Direccion" },
        { "data": "Fijo" },
        { "data": "Email" },
        { "data": "Estado" }
    ],
    "columnDefs": [
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>';
        },
        "targets": 7
        },
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>';
        },
        "targets": 8
        }
        ]
    });
});

The problem is that it redirects me to a page where the json shows me

The result I hope is that this true will go to my funtion reload and enter if and show me the index where I have my datatable.net with the new record created, only update the datatable but not the index page.

    
asked by Pedro Ávila 19.12.2017 в 23:50
source

2 answers

2

I was able to solve it, it was close but I was avoiding the view of the partial view (create) which I had to modify, I will show the implementation:

JsonResult Create Controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Create(ClienteViewModel entity)
    {
        try
        {
            if (ModelState.IsValid)
            {
                config = new MapperConfiguration(cfg => cfg.CreateMap<ClienteViewModel, Cliente>());
                var cliente = config.CreateMapper().Map<Cliente>(entity);
                clienteService.Create(cliente);
                ModelState.Clear();
            }
            var resultado = new { exitoso = true };
            return Json(resultado, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            var resultado = new { exitoso = false };
            return Json(resultado, JsonRequestBehavior.AllowGet);
        }
    }

Partial View Create modified the sumit

<script type="text/javascript" language="javascript">
    $('form').submit(function (e) {
        e.preventDefault();

        var $form = $(this);
        if ($form.valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                cache: false,
                success: function (result) {

                    if (result.exitoso) {
                        $('#myModal').modal('hide');
                        window.reloadTableClientes();
                    }
                },
                error: function (result) {
                }
            });
        }
    });
</script>

In the view of the index the datatable configuration is set in a variable and the function reload is created.

var tableCustomer;
$(document).ready(function() {
    tableCustomer = $("#clientes").DataTable({
        "language": {
            "sProcessing": "Procesando...",
            "sLengthMenu": "Mostrar _MENU_ registros",
            "sZeroRecords": "No se encontraron resultados",
            "sEmptyTable": "Ningún dato disponible en esta tabla",
            "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix": "",
            "sSearch": "Buscar:",
            "sUrl": "",
            "sInfoThousands": ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst": "Primero",
                "sLast": "Último",
                "sNext": "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending": ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        },
        ajax: {
            url: '@Url.Action("ListaClientes", "Cliente")',
    "dataSrc": ''
    },
    columns: [
        { "data": "ClienteId" },
        { "data": "RazonSocial" },
        { "data": "NumeroDocumento" },
        { "data": "Direccion" },
        { "data": "Fijo" },
        { "data": "Email" },
        { "data": "Estado" }
    ],
    "columnDefs": [
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>';
        },
        "targets": 7
        },
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>';
        },
        "targets": 8
        }
        ]
    });
});

function reloadTableClientes() {
    window.tableCustomer.ajax.url('@Url.Action("ListaClientes", "Cliente")').load();
};

That was the changes made.

    
answered by 20.12.2017 / 19:19
source
1

The most advisable thing is to have the same name of the flag so as not to read undefined variables. And in these cases the dictionaries are excellent to return more than one value, if you need it.

 [HttpPost]
//[ValidateAntiForgeryToken] no sé en que influye este tag
public JsonResult Create(ClienteViewModel entity)
{
    var result = new Dictionary<string, object>();
    try
    {
        if (ModelState.IsValid)
        {
            config = new MapperConfiguration(cfg => cfg.CreateMap<ClienteViewModel, Cliente>());
            var cliente = config.CreateMapper().Map<Cliente>(entity);
            clienteService.Create(cliente);
            ModelState.Clear();
        }
        result.Add("SUCCESS", true);
    }
    catch (Exception ex)
    {
         result.Add("SUCCESS", false); 
         result.Add("msnError", ex.Message);
    }
    return Json(result, JsonRequestBehavior.AllowGet);
}    

Then save the configuration of your datatable in a global variable.

var tabla;
$(document).ready(function() {
    tabla = $("#clientes").DataTable({
        "language": {
            "sProcessing": "Procesando...",
            "sLengthMenu": "Mostrar _MENU_ registros",
            "sZeroRecords": "No se encontraron resultados",
            "sEmptyTable": "Ningún dato disponible en esta tabla",
            "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix": "",
            "sSearch": "Buscar:",
            "sUrl": "",
            "sInfoThousands": ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst": "Primero",
                "sLast": "Último",
                "sNext": "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending": ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        },
        ajax: {
            url: '@Url.Action("ListaClientes", "Cliente")',
    "dataSrc": ''
    },
    columns: [
        { "data": "ClienteId" },
        { "data": "RazonSocial" },
        { "data": "NumeroDocumento" },
        { "data": "Direccion" },
        { "data": "Fijo" },
        { "data": "Email" },
        { "data": "Estado" }
    ],
    "columnDefs": [
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>';
        },
        "targets": 7
        },
        {
            "render": function (data, type, row) {
                return '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>';
        },
        "targets": 8
        }
        ]
    });
});

And the ajax must assign its error function. And to refresh the table, use the reload function, since calling only your controller will return the list to the page, not the table.

function reloadTableClientes() {
    $.ajax({
        url: '@Url.Action("Create", "Cliente")',
        success: function (result) {
            //console.log("Perú esta en el mundial")
            alert("Perú esta en el mundial")
            if (result.SUCCESS)
                 tabla.ajax.reload();
        },
        error: function (response) {
            //lo que necesitas en caso de que truene tu controllador
                }
    });
};
    
answered by 20.12.2017 в 00:21