Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Datatables POST array to C# Model

Tags:

c#

datatables

I am sending data to asp mvc using datatables.net structure is like below

draw:1
columns[0][data]:first_name
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:last_name
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
order[0][column]:0
order[0][dir]:asc
start:0
length:10
search[value]:
search[regex]:false

How can I pick/bind this data to c# class which is parameter of Action method, actually start, length, draw maps but columns[n][nnn] give null

My c# model class is public class DataTableModel {

    public string draw { get; set; }
    public ICollection<Columns> columns { get; set; }
    //public string[] order { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Order> order { get; set; }
    public int recordsTotal { get; set; }
    public int recordsFilter { get; set; }

    public DataTableModel()
    {
        columns = new List<Columns>();
        order = new List<Order>();
    }
}

public class Columns
{
    public string data { get; set; }
    public string name { get; set; }
    public string searchable { get; set; }
    public string orderable { get; set; }
    public List<Search> search { get; set; }
}

public class Search
{
    public bool regex { get; set; }
    public string value { get; set; }
}

public class Order
{
    public string column { get; set; }
    public string dir { get; set; }
}

Thanks

like image 375
Irfan Ashraf Avatar asked Sep 28 '22 17:09

Irfan Ashraf


2 Answers

No this is not the case I am using latest version which do not post iSortCol_n. Answer is I was not including 'contentType': "application/json". That's why I was picking null columns list in mvc action parameter. Once I place it mvc map all the fields.

 var table =   $('#example').dataTable({
        "processing": true,
        "serverSide": true,
        'ajax': {
            'type': 'POST',
            'contentType': "application/json",
            'url': '/TestDistributor/GetAllForGrid',
            'data': function (d) {
                console.log(JSON.stringify(d));
                return JSON.stringify(d);
            }
        },
        "columns": [
        { 'data': 'DistributorCode' },
        { 'data': 'DistributorName' },
        { 'data': 'AreaCode' },
        { 'data': 'TownCode' },
        { 'data': 'CityCode' },
        ]
    });
like image 143
Irfan Ashraf Avatar answered Oct 05 '22 07:10

Irfan Ashraf


Here are the classes

public class JQDTParams
    {
        public int draw { get; set; }

        public int start { get; set; }
        public int length { get; set; }


        public JQDTColumnSearch  /*Dictionary<string, string>*/ search { get; set; }
        public List<JQDTColumnOrder/*Dictionary<string, string>*/> order { get; set; }
        public List<JQDTColumn/*Dictionary<string, string>*/> columns { get; set; }

    }


    public enum JQDTColumnOrderDirection
    {
        asc, desc
    }

    public class JQDTColumnOrder
    {
        public int column { get; set; }
        public JQDTColumnOrderDirection dir { get; set; }
    }
    public class JQDTColumnSearch
    {
        public string value { get; set; }
        public string regex { get; set; }
    }

    public class JQDTColumn
    {
        public string data { get; set; }
        public string name { get; set; }
        public Boolean searchable { get; set; }
        public Boolean orderable { get; set; }
        public JQDTColumnSearch search { get; set; }
    }

And Usage

HTML

<div>

    <table id="aractipiListesi" class="display" cellspacing="0" width="100%">
        <thead>
            <tr class="filter-input">
                <th>PK</th>
                <th>Markası</th>
                <th>Modeli</th>
                <th></th>
            </tr>
            <tr>
                <th>PK</th>
                <th>Markası</th>
                <th>Modeli</th>
                <th></th>
            </tr>
        </thead>
    </table>

    <script type="text/javascript">

      $(document).ready(function () {
          $('#aractipiListesi').DataTable({
              "processing": true,
              "serverSide": true,
              "filter": true,
              "pageLength": 8,
              "columns": [
                  {
                      "name": "ID",
                      "orderable": false
                  },
                  {
                      "name": "MARKAADI",
                      "orderable": true
                  },
                  {
                      "name": "TIPADI",
                      "orderable": true
                  },
                  {
                      "name": "SEC",
                      "orderable": false
                  }
              ],
              "ajax":
                  {
                      url: "@Url.Action("AracTipiAra", "Common", new { area = "" })",
                      type: "post"
                  },
              "columnDefs":
                  [
                      {
                          "render": function (data, type, row) { return AracTipiListesiTableDropDownToggle(data, type, row); },
                          "targets": [3]
                      },
                      {
                          "visible": false,
                          "targets": [0]
                      }
                  ],

              "language": DTConstants.Language


          });

          var aractipi_filtrelenecekBasliklar = ['Markası', 'Modeli'];
          // Setup - add a text input to each footer cell
          $('#aractipiListesi thead .filter-input th').each(function () {
              var title = $(this).text();
              if (title != '' && $.inArray(title, aractipi_filtrelenecekBasliklar) >= 0) {
                  $(this).html('<input type="text" placeholder="' + title + ' Ara" />');
              }
          });

          // DataTable
          var table = $('#aractipiListesi').DataTable();

          // Apply the search
          table.columns().every(function () {
              var that = this;

              $('input', this.footer()).on('keyup change', function () {
                  if (that.search() !== this.value) {
                      that.search(this.value).draw();
                  }
              });
          });
        });
    </script>


</div>

Controller

 public JsonResult AracTipiAra(JQDTParams param)
        {
            using (var db = new MBOSSEntities())
            {
                var q = from x in db.VW_ARACMARKATIPI select x;
                var nonfilteredcount = q.Count();
                //filter 
                //-------------------------------------------------------------------
                foreach (var item in param.columns)
                {
                    var filterText = item.search.value;
                    if (!String.IsNullOrEmpty(filterText))
                    {
                        filterText = filterText.ToLower();
                        switch (item.name)
                        {
                            case "MARKAADI":
                                q = q.Where(
                       x =>
                           x.MARKAADI.ToLower().Contains(filterText)

                   );
                                break;
                            case "TIPADI":
                                q = q.Where(
                       x =>
                           x.TIPADI.ToLower().Contains(filterText)

                   );
                                break;
                        }
                    }
                }
                //order
                //-------------------------------------------------------------------
                foreach (var item in param.order)
                {
                    string orderingFunction = "MARKAADI";
                    switch (item.column)
                    {
                        case 1: orderingFunction = "MARKAADI";
                            break;

                        case 2: orderingFunction = "TIPADI";
                            break;

                    }

                    q = OrderClass.OrderBy<VW_ARACMARKATIPI>(q, orderingFunction, item.dir.GetStringValue());
                }

                //result
                //-------------------------------------------------------------------
                var filteredCount = q.Count();
                q = q.Skip(param.start).Take(param.length);
                var data = q.ToList()
                    .Select(r => new[] {
                        r.ARACMARKAPK.ToString(),
                        r.MARKAADI,
                        r.TIPADI,
                    }

                    );
                return Json(new
                {
                    draw = param.draw,
                    recordsTotal = nonfilteredcount,
                    recordsFiltered = filteredCount,
                    data = data
                }, JsonRequestBehavior.AllowGet);

            }

        }
like image 29
Fatih Avatar answered Oct 05 '22 07:10

Fatih