Get the client id from a selected Datatable line

Asked

Viewed 2,209 times

1

How to Get a Customer Id from a DataTable This column is hidden ? When I click on the line DataTable 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);
    }
  • Is datatable data coming as? Paged by the server? Do you generate everything in HTML and then convert it to datatable? There are a few ways to do this and the way the table is generated can influence.

  • Erick the processing is being done on the server, I added in the question to Action that returns the data to the Datatable.

2 answers

1

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

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

and then retrieve at the line click:

$('#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);
        });

1

Hello, one way to do this is to use fnGetData

For this after declaring your table you declare the get date event for Row Face (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 http://datatables.net/api#fnGetData

Edited

Another thing, the right thing would be for you to do

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

And not call after the var table = $("#tblCLiente"). Datatable() It’s like you’ve recreated Datatable.

  • Thanks Erick but it doesn’t work

  • @Adrianocorder Give an error? Returns empty? What happens when you use fnGetData?

  • You are right Erick on the table variable I already changed, but I am in the same, that is: Not the error and does not return anything, simply when I click on the Datatable line nothing happens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.