将Datatables POST数组转换为C#Model

时间:2015-02-18 07:57:42

标签: c# datatables

我使用datatables.net结构向asp mvc发送数据如下所示

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

如何选择/绑定此数据到c#类,这是Action方法的参数,实际上是start,length,draw map但是     列[N] [NNN] 给空

我的c#模型类是     公共类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; }
}

由于

2 个答案:

答案 0 :(得分:2)

不是这不是我使用的最新版本没有发布iSortCol_n。答案是我不包括'contentType':“application / json”。这就是我在mvc动作参数中选择空列列表的原因。一旦我放置它mvc映射所有字段。

 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' },
        ]
    });

答案 1 :(得分:1)

以下是课程

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

和用法

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>

控制器

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

            }

        }