Populate data a datatable from a JSON

3

Working with ASP.NET MVC, I am using the library DataTable.net

I am bringing data from the database through a JsonResult that returns the information in plain text.

Method

// GET: Cliente
    public ActionResult Index()
    {
        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);
    }

From the HTML

<script type="text/javascript" language="javascript">
$(document).ready(function() {
    $("#clientes").DataTable({
        paging: true,
        searching: true,
        bProcessing: true,
        "ajax": {
            "url": "Cliente/Index",
            "columns": [
                { "data": "ClienteId" },
                { "data": "RazonSocial" },
                { "data": "NumeroDocumento" },
                { "data": "Direccion" },
                { "data": "Fijo" },
                { "data": "Email" },
                { "data": "Estado" }
            ],
            "dataType": "json"
        },
        "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"
            }
        }
    });
});

The problem is that it shows me a page with the following information

I think the issue is to leave the Index as ActionResult and create a JsonResult method that loads the table.

Updating how I have my methods. Controller

 // GET: Cliente
    public ActionResult Index()
    {
        return View();
    }

    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);
    }

HTML

<script type="text/javascript" language="javascript">
$(document).ready(function() {
    $("#clientes").DataTable({
        //paging: true,
        //searching: true,
        //bProcessing: true,
        "ajax": {
            "url": "@Url.Action("ListaClientes")",
            "dataSrc": '',
            "type": "GET",
            "columns": [
                { "data": "ClienteId" },
                { "data": "RazonSocial" },
                { "data": "NumeroDocumento" },
                { "data": "Direccion" },
                { "data": "Fijo" },
                { "data": "Email" },
                { "data": "Estado" }
            ],
            //"dataType": "json"
        },
        "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"
            }
        }
    });
});

Error DataTables warning: table id = clients - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see

    
asked by Pedro Ávila 07.12.2017 в 20:02
source

1 answer

1

My doubt is the same as that of JuankGlezz since if your Index method returns a Json you can not call the Index view at the same time. But I'm going to give you a clear example of your question.

We have the Index method which calls the Index view that contains a Table (DataTable) where the clients are displayed.

    public ActionResult Index()
    {
        return View();
    }

The view has the following:

    @*ESTO YA NO LO NECESITAS YA QUE LOS CLIENTES VIENEN EN UN JSON*@
    @*@model IEnumerable<WebApp1.Models.Cliente>*@

    @{
       ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    <p>
      @Html.ActionLink("Create New", "Create")
    </p>
<table id="clientes" class="display">
    <thead>
        <tr>
            <th>
                Id
            </th>
            <th>
                RazonSocial
            </th>
            <th>
                NumeroDocumento
            </th>
            <th>
                Direccion
            </th>
            <th>
                Fijo
            </th>
            <th>
                Email
            </th>
            <th>
                Estado
            </th>
        </tr>
    </thead>
</table>
@section scripts
{
    <script>
        $(document).ready(function () {
            $("#clientes").DataTable({
                ajax: {
                    "url": "@Url.Action("ListadoClientes")",
                    "dataSrc": ''
                },
                columns: [
                    { "data": "ClienteId" },
                    { "data": "RazonSocial" },
                    { "data": "NumeroDocumento" },
                    { "data": "Direccion" },
                    { "data": "Fijo" },
                    { "data": "Email" },
                    { "data": "Estado" }
                ]
            });
        });
    </script>
}

If you look at the script, it was shorter when you delete parameters that are called by default, such as busqueda , paginación and filtrado . The interesting part is where the option url is defined which I define with the Helper @Url.Action that ASP brings. This defaults to our controller as GET , so I create a method which returns a Json with a list of Clients. Staying this way:

    public class ClienteController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: /Cliente/
        public ActionResult Index()
        {
            ListadoClientes();
            return View();
        }

        public JsonResult ListadoClientes()
        {
            var clientes = db.Clientes.ToList();
            return Json(clientes, JsonRequestBehavior.AllowGet);
        }
        .......
}

JsonRequestBehavior.AllowGet ALLOWS YOU TO RESPOND WITH JSON TO TYPE GET REQUESTS, IF YOU DO NOT PUT IT YOU WOULD GIVE IT AN ERROR 500. Another important part is to declare "dataSrc": '' in your scrip to work with a Json array. This way it works perfectly I hope it helps you

    
answered by 08.12.2017 / 23:34
source