Get the client ID of a selected row from the DataTable

1

How do I get the client ID of a DataTable and this column is hidden? When I click on the DataTable line I will need this ID to display in another View with Customer details.

I have the following code

  @model IEnumerable<Dominio.Entidade.TBCliente>

@{
    ViewBag.Title = "CLIENTE";
    Layout = "~/Areas/Administrativo/Views/Shared/_AdministrativoLayout.cshtml";
}


<table id="tblCLiente" class="table table-hover table-bordered table-condensed table-responsive table-striped small">
    <thead>
        <tr>
            <th>ID</th>
            <th>NOME</th>
            <th>TIPO</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>


@section Scripts {
    <script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
    <script src="//cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
    <link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />

    <script type="text/javascript">

        $(document).ready(function () {

            var table = $("#tblCLiente").DataTable({
                "bProcessing": true,
                "bServerSide": true,
                "scrollY": "50vh",
                "scrollCollapse": true,

                "language": {
                    "lengthMenu": "Exibir _MENU_ registros por páginas",
                    "zeroRecords": "NÃO LOCALIZADO",
                    "info": "Exibir de _PAGE_ até _PAGE_",
                    "infoEmpty": "REGISTRO NÃO LOCALIZADO!",
                    "infoFiltered": " (de um total de_MAX_ registros.)",

                },
                "sAjaxSource": "BuscarCliente",
                "aoColumns": [
                                { "sName": "TBCLIENTEID", "mData": "TBCLIENTEID", "bVisible": false },
                                { "sName": "NMCLIENTE", "mData": "NMCLIENTE" },
                                { "sName": "TPCLIENTE", "mData": "TPCLIENTE" }
                ],
                "sPaginationType": "full_numbers"
            });



            $('#tblCLiente tbody').on('click', 'tr', function () {

                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                }
                else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
            });

            $('#button').click(function () {
                table.row('.selected').remove().draw(false);
            });

            table.$('tr').click(function () {
                var data = table.fnGetData(this);
                alert(data);
        });

        });

    </script>
}

ACTION

public JsonResult BuscarCliente()
    {
        string echo = Request.Params["sEcho"].ToString();
        string iColumns = Request.Params["iColumns"].ToString();
        string sColumns = Request.Params["sColumns"].ToString();
        int iDisplayStart = int.Parse(Request.Params["iDisplayStart"].ToString());
        int iDisplayLength = int.Parse(Request.Params["iDisplayLength"].ToString());
        string mDataProp_0 = Request.Params["mDataProp_0"].ToString();
        string sSearch = Request.Params["sSearch"].ToString();
        string iSortCol_0 = Request.Params["iSortCol_0"].ToString();
        string sSortDir_0 = Request.Params["sSortDir_0"].ToString();
        string iSortingCols = Request.Params["iSortingCols"].ToString();
        string bSortable_0 = Request.Params["bSortable_0"].ToString();
        int regExibir = iDisplayLength;
        int startExibir = iDisplayStart;

        List<TBCliente> lClienteFiltrado = new List<TBCliente>();
        List<TBCliente> lTotalCliente = _IRepositorio.ListarCliente();

        if (!string.IsNullOrWhiteSpace(sSearch))
        {
            lClienteFiltrado = lTotalCliente.Where(x => x.NMCLIENTE.ToUpper().Contains(sSearch.ToUpper())).ToList<TBCliente>();
        }
        else
        {
            lClienteFiltrado = lTotalCliente;
        }

        if (iDisplayStart > lClienteFiltrado.Count)
            startExibir = 0;
        if (iDisplayStart + iDisplayLength > lClienteFiltrado.Count)
            regExibir = lClienteFiltrado.Count - startExibir;

        if (sSortDir_0 == "asc")
        {
            if (iSortCol_0 == "0")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.TBCLIENTEID).ToList<TBCliente>();
            if (iSortCol_0 == "1")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.NMCLIENTE).ToList<TBCliente>();
            if (iSortCol_0 == "2")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.TPCLIENTE).ToList<TBCliente>();
        }
        else
        {
            if (iSortCol_0 == "0")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.TBCLIENTEID).ToList<TBCliente>();
            if (iSortCol_0 == "1")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.NMCLIENTE).ToList<TBCliente>();
            if (iSortCol_0 == "2")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.TPCLIENTE).ToList<TBCliente>();
        }

        var Resultado = new
        {
            sEcho = echo,
            iTotalRecords = lTotalCliente.Count,
            iTotalDisplayRecords = lClienteFiltrado.Count,
            //iDisplayLength = 10,
            aaData = lClienteFiltrado.ToList<TBCliente>().GetRange(startExibir, regExibir)
        };
        return Json(Resultado, JsonRequestBehavior.AllowGet);
    }
    
asked by anonymous 16.09.2015 / 14:35

2 answers

1

Hello, one way to do this is to use fnGetData

To do this, after declaring your table you declare the get date event for row (row) of your table.

table.$('tr').click( function () {
    var data = table.fnGetData( this );
    // a variavel data vai conter ou um array ou objeto contendo todos os dados da sua row
  } );

Official documentation link

Edited

Another thing, the more correct would you do

var table = $("#tblCLiente").DataTable({
                "bProcessing": true,
                "bServerSide": true, ....

And do not call the var table = $ ("# tblCreate") then DataTable () as if you were recreating the DataTable.     

16.09.2015 / 15:05
1

I found the solution and it was for those who go through the same situation as me, the solution was to add the value of the client id to the "id" attribute of the "rowCallback": parameter of the ajax request:

           "rowCallback": function (row, data) {
                $(row).attr("id", data.TBCLIENTEID);
            },
            "sPaginationType": "full_numbers"ódigo aqui

and then retrieve in the click of the line:

$('#tblCLiente tbody').on('click', 'tr', function () {
            var id = this.id;
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        });

        $('#button').click(function () {
            table.row('.selected').remove().draw(false);
        });
    
17.09.2015 / 00:20