jQuery DataTables通过ajax加载列和数据

时间:2013-04-24 04:45:31

标签: jquery asp.net-mvc datatables

按照此链接进行ajax调用以动态加载Jquery Datatables

http://datatables.net/forums/discussion/3442/x&page=1#Item_10

在我开始尝试之前,我在这里遇到了我的想法。

那么DataTables如何发送iDisplayLength,iDisplayStart,sEcho等属性来制作分页和显示记录。

我该如何处理?

Link的示例代码,供快速参考

$.ajax( {
        "dataType": 'text',
        "type": "GET",
        "url": "dtJSON.txt",
        "success": function (dataStr) {
            var data = eval( '('+dataStr+')' );
          $('#example').dataTable({
                "aaSorting": [[0, "desc"]],
                "aaData": data.aaData,
                "aoColumns": data.aoColumns,
                "bScrollCollapse": true,
                "bFilter": false,
                "sPaginationType": "full_numbers",
                "bJQueryUI": true,
                "aoColumnDefs": data.aoColumnDefs
          });
        }
    } );

我可以使用ajax获取数据和列详细信息但是如何处理发送到MVC中控制器的参数?

非常感谢一些帮助:)

由于

2 个答案:

答案 0 :(得分:1)

我的推荐是在客户端使用把手和应用数据表后呈现de table:

您需要一张空表:

<table id="mytable">
  <thead>
      <tr>
          <th>Col 1</th>
          <th>Col 2</th>
          <th>Col 3</th>
      </tr>
  </thead>
  <tbody id="table_data_container">
      <!-- Populated by JS -->
  </tbody>
</table>

ajax请求,不要在服务器端进行分页,datatables会在客户端为你处理它,这意味着你不必将当前页面发送到服务器,你只需返回所有可用行,如果行数非常高,请尝试强制用户按名称,ID或其他方式进行搜索,然后您可以在ajax请求中发送该过滤器。

$.ajax({
    type: method,
    url: url,
    async: async,
    data: parameters,
    dataType: dataType,
    success: function(json){
        var container = $('#table_data_container');
        //your response should be an object like { items : [item,item,item,...] }
        var template = '{{#each item}}<tr><td>{{this.col1}}</td><td>{{this.col1}}</td><td>{{this.col1}}</td></tr>{{/each}}' //visit http://handlebarsjs.com/ for info
        RenderJson(json,template,container); //this will generate thehtml for the rows and append it to the table
        $('#mytable').dataTable();
    },
    error: function(response){
        alert('Error!');
    }
});

渲染功能:

function RenderJson(json,template,container) {
    var compiledTemplate = Handlebars.compile(template);
    var html = compiledTemplate(json);
    $(container).html(''); //remove previous content
    $(container).html(html); //set new content
}

希望它有所帮助;)

答案 1 :(得分:0)

这将有助于您更改dropdownlist并按钮提交填充数据表中的数据。

注意:当您处理datatable时,此行有助于传递表单中的其他控件值。

 @using (@Html.BeginForm("action", "controllername", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <div class="table-responsive">
        <div class="col-sm-12">
            <div class="row">
                <div class="col-md-3">
                    <label>Report type</label>
                </div>
                <div class="col-md-3">

                    @Html.DropDownList("ReportTypeEnum", new SelectList(Enum.GetValues(typeof(appname.Model.ReportTypeEnum))), new {@class = "form-control"})
                </div>
                <div class="col-md-3">
                    <button class="btn btn-primary col-sm-12">Submit</button>
                </div>
in datatable binding model in ajax call as below:


 [ "ajax": {   "url": '@Url.Action("action", "controller")',
                                    'type': 'GET',
                                    "data": function (d) { d.reportType = $('#ReportTypeEnum :selected').text(); } //JSON.stringify({ reportType: varReportTypeEnum })
                                }]

    this code will for controller
dropdown enum: code in model:
 public enum ReportTypeEnum
    {

        Yes,
        No,
        NoResponse          
    }
and below datatable ajax calling method 
     public JsonResult ajaxcallmethod([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel, string reportType)// string reportType
            {

                // below is we are taking dropdownchange value based on that we load the data into datatable.
                yourmodel model = new yourmodel ();
                if (reportType.ToLower() == ReportTypeEnum.Yes.ToString().ToLower())
                {
                    model.ReportTypeEnum = ReportTypeEnum.Yes;
                }
                else if (reportType.ToLower() == ReportTypeEnum.No.ToString().ToLower())
                {
                    model.ReportTypeEnum = ReportTypeEnum.No;
                }
                else if (reportType.ToLower() == ReportTypeEnum.NoResponse.ToString().ToLower())
                {
                    model.ReportTypeEnum = ReportTypeEnum.NoResponse;
                }

    data =// here model call 


                return Json(new DataTablesResponse((int)requestModel.Draw, data, transactionsListingResponse.PagerResource.ResultCount, transactionsListingResponse.PagerResource.ResultCount), JsonRequestBehavior.AllowGet);
            }