Asp.net Mvc Datatable does not render correctly

2

I am working with Asp.net Mvc and jquery.Datatables, and I have the following problem.

in a page, I'm showing process data ... and for that I defined an html table, and with datatable I defined the following JS function to control the load.

@section scripts{
<script src="~/Scripts/DataTables/jquery.dataTables.js" type="text/javascript"></script>
<link href="~/Content/DataTables/css/demo_table.css" rel="stylesheet" type="text/css" />
<script>
    $(document).ready(function () { 
        var oTable = $('#TablaProcesosDtt').dataTable({
            "bServerSide": true,
            "sAjaxSource": "/Kam/Proceso/GetProcesosKam",
            "bProcessing": true,
            "aoColumns": [
                { "sName": "Id" },
                { "sName": "Proceso" },
                { "sName": "Cliente" },
                { "sName": "Fecha" },
                { "sName": "Cargados" },
                { "sName": "Validados" },
                { "sName": "Erroneos" },
                { "sName": "Estado" },
                {
                    "sName": "Acciones",
                    "bSearchable": false,
                    "bSortable": false,
                    "fnRender": function (oObj) {
                        console.log(oObj.aData[0]);
                        return '<a href="#" onclick="CargarInfoAsistencia(' + oObj.aData[0] + ')>Cargar</a>';
                   }
                }
            ]
        });
    });
</script>
                    
asked by Luis Gabriel Fabres 13.12.2018 в 15:34
source

1 answer

4

In case someone else is useful, I found the right way to do this for asp.net with mvc. I leave here an example

html

<div id="GridInfoProcesosDtt" class="display">
<table id="TablaProcesosDtt" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Proceso</th>
            <th>Cliente</th>
            <th>Fecha</th>
            <th>Registros Cargados</th>
            <th>Registros Validados</th>
            <th>Registros Erroneos</th>
            <th>Estado</th>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

JS

    <script src="~/Scripts/DataTables/jquery.dataTables.js" type="text/javascript"></script>
<link href="~/Content/DataTables/css/demo_table.css" rel="stylesheet" type="text/css" />
<script>
    $(document).ready(function () {

        var KamId = 12; // este parametro debe venir desde el controller

        $("#GridInfoProcesosDtt").show();
        $("#GridInfoFichaDtt").hide();


        var oTable = $('#TablaProcesosDtt').dataTable({
            "bServerSide": true,
            "sAjaxSource": "/Kam/Proceso/GetProcesosKam",
            "bProcessing": true,

            "fnServerParams": function (aoData) {
                aoData.push({ "name": "sKamId", "value": KamId })
            },

            "aoColumns": [
                { "sName": "Id" },
                { "sName": "Proceso" },
                { "sName": "Cliente" },
                { "sName": "Fecha" },
                { "sName": "Cargados" },
                { "sName": "Validados" },
                { "sName": "Erroneos" },
                { "sName": "Estado" },
                {
                    "sName": "Ver",
                    "bSearchable": false,
                    "bSortable": false,
                    "mRender": function (data, type, full) {
                        var id = full[0]; //ProcesoId
                        return "<a href='javascript:GetFichasProceso(" + id + ");'>Ver</a>";
                    }
                },
                {
                    "sName": "Cargar",
                    "bSearchable": false,
                    "bSortable": false,
                    "mRender": function (data, type, full) {
                        var id = full[0]; //ProcesoId
                        return "<a href='javascript:CargarExcel(" + id + ");'>Cargar</a>";
                    }
                }
            ]
        });
    });
</script>

in the controller, you have to use a class to pass parameters for the page.

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TW_Web.Areas.Kam.Models
{
    /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho { get; set; }

        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch { get; set; }

        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength { get; set; }

        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart { get; set; }

        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns { get; set; }

        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols { get; set; }

        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns { get; set; }

    }

}

Controller:

            /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table. 
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult GetProcesosKam(TW.Intranet.Areas.Kam.Models.JQueryDataTableParamModel param, string sKamId)
        {

            int KamId = Convert.ToInt32(sKamId);
            TW.Business.Kam.Proceso ck = new Proceso();
            List<VM_ProcesoKam> lstProcesosKam = ck.GetProcesosKam(KamId);

            //foreach (VM_ProcesoKam proceso in lstProcesosKam)
            //{
            //    proceso.Acciones = "<button>editar</button>";
            //}


            #region Filtros
            List<VM_ProcesoKam> filteredProcesos;
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered 
                var clienteFilter = Convert.ToString(Request["sSearch_1"]);
                var procesoFilter = Convert.ToString(Request["sSearch_2"]);

                //Optionally check whether the columns are searchable at all 
                var isClienteSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isProcesoSearchable = Convert.ToBoolean(Request["bSearchable_2"]);

                filteredProcesos = ck.GetProcesosKam(KamId)
                   .Where(c => isClienteSearchable && c.Cliente.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isProcesoSearchable && c.Proceso.ToLower().Contains(param.sSearch.ToLower())).ToList();
            }
            else
            {
                filteredProcesos = lstProcesosKam;
            }
            #endregion

            #region Ordenamiento
            var isProcesoSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isClienteSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isFechaSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var isEstadoSortable = Convert.ToBoolean(Request["bSortable_4"]);

            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<VM_ProcesoKam, string> orderingFunction = (c => sortColumnIndex == 1 && isProcesoSortable ? c.Proceso :
                                                           sortColumnIndex == 2 && isClienteSortable ? c.Cliente :
                                                           sortColumnIndex == 3 && isFechaSortable ? c.Fecha.ToString() :
                                                           sortColumnIndex == 4 && isEstadoSortable ? c.Estado :
                                                           "");

            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredProcesos = filteredProcesos.OrderBy(orderingFunction).ToList();
            else
                filteredProcesos = filteredProcesos.OrderByDescending(orderingFunction).ToList();
            #endregion

            var displayedProcesos = filteredProcesos.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedProcesos
                         select new[] { Convert.ToString(c.ProcesoId),
                                        c.Proceso,
                                        //Convert.ToString(c.ClienteId),
                                        c.Cliente,
                                        Convert.ToString(c.Fecha),
                                        Convert.ToString(c.Cargados),
                                        Convert.ToString(c.Validados),
                                        Convert.ToString(c.Erroneos),
                                        Convert.ToString(c.Estado),
                                        c.Acciones};
            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = lstProcesosKam.Count(),
                iTotalDisplayRecords = filteredProcesos.Count(),
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

Greetings

    
answered by 13.12.2018 в 16:39