在 c# 中将多维 JavaScript 数组绑定为方法参数

Binding a multi dimentional javascript array as method parameter in c#

本文关键字:绑定 数组 方法 参数 JavaScript      更新时间:2023-09-26

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

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

假设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);
 }

其他信息。

这是类

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