将多维javascript数组绑定为c#中的方法参数

时间:2014-12-19 12:21:29

标签: javascript c# asp.net-mvc jquery-datatables

您好我正在寻找一种绑定此数据的方法:

columns[0][data]:0
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:1
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:2
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
columns[3][data]:3
columns[3][name]:
columns[3][searchable]:true
columns[3][orderable]:true
columns[3][search][value]:
columns[3][search][regex]:false
columns[4][data]:4
columns[4][name]:
columns[4][searchable]:true
columns[4][orderable]:true
columns[4][search][value]:
columns[4][search][regex]:false
columns[5][data]:5
columns[5][name]:
columns[5][searchable]:true
columns[5][orderable]:true
columns[5][search][value]:
columns[5][search][regex]:false
columns[6][data]:6
columns[6][name]:
columns[6][searchable]:true
columns[6][orderable]:true
columns[6][search][value]:
columns[6][search][regex]:false
columns[7][data]:7
columns[7][name]:
columns[7][searchable]:true
columns[7][orderable]:true
columns[7][search][value]:
columns[7][search][regex]:false
columns[8][data]:8
columns[8][name]:
columns[8][searchable]:true
columns[8][orderable]:false
columns[8][search][value]:
columns[8][search][regex]:false

到我的方法到目前为止我尝试了一个对象数组,但它在这里不起作用是我的方法定义:

public async Task<JsonResult> DriveDataTable(jQueryDataTableParamModel param)

和jQueryDataTableParamModel类:

public class jQueryDataTableParamModel
{
    //Paging first record indicator. This is the start point in the current data set (0 index based - i.e. 0 is the first record).
    public int start { get; set; }
    // global search keyword
    public string search { get; set; }
    // Number of records that should be shown in table
    public int length { get; set; }
    //represent the index of column which is to ordered 
    public int orderByCol { get; set; }
    //order direction (asc or desc)
    public string orderDirection { get; set; }

    public object[] columns { get; set; }

}

2 个答案:

答案 0 :(得分:2)

假设myArr是你的javascript多维数组,你可以用这种方式将它传递给c#

JSON.stringify(myArr)

然后在c#类中你可以改变

中的属性
public object columns { get; set; }

但我认为也是

public string columns { get; set; }应该有效

然后服务器端你可以用某种方式反序列化

通常我通过javascript发送序列化对象,当他们以字符串格式返回到我的C#方法时,我以这种方式反序列化它们

 [HttpPost]
 public ActionResult MyMethod(string model)
 {
     //model in this case is what JSON.stringify(myArr) sends
     var jsSettings = new JsonSerializerSettings();
     jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
     var deserializedModel = JsonConvert.DeserializeObject<MyComplexType>(model, jsSettings);
     //now deserializedModel is of type MyComplexType
     return PartialView("~/Views/Shared/Somefile.cshtml", deserializedModel);
 }

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

            }

        }