【问题标题】:Binding a multi dimentional javascript array as method parameter in c#在c#中将多维javascript数组绑定为方法参数
【发布时间】:2014-12-19 12:21:29
【问题描述】:

嗨,我正在寻找一种方法来绑定这些数据:

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

}

【问题讨论】:

  • 您是在尝试将数据传递到控制器还是从控制器传递到网格?你怎么通过它,AJAX?如果您将其传递给控制器​​,则参数类型错误。请提供更多详细信息,我会尽力提供帮助
  • 我正在使用 jquery-datable 并且您猜我正在通过 AJAX 发布给定的多维数组。那么为什么您认为参数的类型错误,它已经适用于其他参数

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


【解决方案1】:

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

【讨论】:

  • 感谢您解决问题的好方法。我试过了,它奏效了,但我真的想知道是否有更紧凑的问题解决方案......
  • 我做了一些更新,只是为了展示如何在一个工作示例中使用我的代码,我一直使用这个解决方案,希望它可以帮助你。
  • 谢谢 :) 我在您更新之前继续前进,并做了与更新中所示几乎相同的想法(顺便将复杂的 javascript 数组转换为字符串并将其传递给服务器确实是个好主意 :)) .
【解决方案2】:

附加信息。

这里是类

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

            }

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2022-01-09
    • 2010-09-05
    • 2013-04-01
    • 2012-11-24
    相关资源
    最近更新 更多