【问题标题】:How to refresh DataTables plug-in for jQuery如何刷新 jQuery 的 DataTables 插件
【发布时间】:2017-05-16 13:26:00
【问题描述】:

要求是:

显示过滤表格结果的单选按钮。

我正处于此功能正常工作的最边缘,但我不知道如何重新加载 DataTable。 onclick 执行后,客户端正确地从服务器检索数据,但我在尝试刷新时继续收到 DataTable 运行时错误。单击“推荐”单选按钮后,下图以 JSON 格式返回正确的数据:

View.vbhtml

@Imports Project.Domain.Models
@Imports Project.Web.ViewModels
@ModelType VaccineViewModel
@Code
   Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
@section Styles
   @Styles.Render("~/StylesWithDataTables")
End Section

@section scripts
  <script type="text/javascript">
    var app_base = '@Url.Content("~/")';
  </script>
  @Scripts.Render("~/ScriptsWithDataTables")
  @Scripts.Render("~/Scripts/customajax/vaccine.index.js")
End Section

<div class="page-content">
<div class="row">
    <div class="col-md-8 col-md-offset-2">
          @Html.Partial("_GenericMessage")
    </div>
</div>
<div class="portlet box green">
    <div class="portlet-title">
        <div class="caption">
            List
        </div>
    </div>
    <div class="portlet-body form">
        <div class="form-body">
            <div class="row" style="padding-bottom: 10px; padding-top: 10px;">
                <div class="col-md-12">
                    <a class="btn-sm btn-primary" href="@Url.Action("Add", "Vaccine")"><i class="fa fa-plus"></i>&nbsp;Add New </a>
                </div>
            </div>
            <div class="row" style="padding-bottom: 10px; padding-top: 10px;">
                <div class="col-md-12">
                    <label>
                        <input checked type="radio" value="VFC" group="filter" data-filter="1"> VFC
                        <input type="radio" value="Non-VFC" group="filter" data-filter="2"> Non-VFC
                        <input type="radio" value="Recommended" group="filter" data-filter="3"> Recommended
                        <input type="radio" value="Non-Recommended" group="filter" data-filter="4"> Non-Recommended
                        <input type="radio" value="Active" group="filter" data-filter="5"> Active
                        <input type="radio" value="Inactive" group="filter" data-filter="6"> Inactive
                    </label>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <div class="portlet light portlet-fit portlet-datatable ">
                            <div class="portlet-body">
                                @Html.Partial("~/Views/Vaccine/_Vaccines.vbhtml", New AjaxVaccineFilterViewModel() With {.Vaccines = Model.Vaccines})
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</div>

PartialView.vbhtml

@Imports Project.Domain.Models
@Imports Project.Web.ViewModels
@ModelType AjaxVaccineFilterViewModel

<div class="tablecontainer">
 <table class="table table-striped table-bordered table-hover table-checkable order-column" id="sample_4">
    <thead>
        <tr>
            <th> </th>
            <th> Vaccine </th>
        </tr>
    </thead>
    <tbody>
        @Code
            For Each item As Vaccine In Model.Vaccines
            @<tr class="odd gradeX">
                <td> <a href="@Url.Action("Edit", "Vaccine", New With {Key .id = item.VaccineId})" class="btn-sm btn-primary">Edit</a></td>
                <td> @item.VaccineAbbreviation.ToUpper </td>
            </tr>
            Next
        End Code
    </tbody>
 </table>
</div>

vaccine.index.js

$(function () {
// Someone has clicked one of the filter radio buttons
 $('input[type=radio]').click(function () {
    var o = {};
    o.filter = $(this).data("filter");

    // Make a viewModel instance
    var viewModel = new Object();
    viewModel.Filter = o.filter;

    //Ajax call to post the viewModel to the controller
    var strung = JSON.stringify(viewModel);

   $.ajax({
        url: app_base + 'Vaccine/ReloadIndex',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: strung,
        success: function (data) {
            //$('.tablecontainer').html(data);
            //$('#sample_4').DataTable().ajax.reload();
            oTableReq = $('#sample_4').DataTable();
            oTableReq.destroy();
            try {
                oTableReq = $('#sample_4').DataTable({
                    "bProcessing": true,
                    responsive: false,
                    //"autoWidth": false,
                    "scrollX": true,
                    data: data,
                    columns: [
         {
             "data": "VaccineId", "width": "50px", "render": function (data) {
                 return '<a class="btn-sm btn-primary" href="/Vaccine/Edit/' + data + '">Edit</a>';
             }
         },
        { "data": "VaccineAbbreviation", "autoWidth": true }
                    ]
                });
            } catch (exception) {
                message(exception, "Attention", "error");
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            ShowUserMessage("Error: " + xhr.status + " " + thrownError);
        }
    });
 });
});

VaccineController.vb

<HttpGet>
Function Index() As ActionResult
    Dim viewModel As New VaccineViewModel
    viewModel.Vaccines = _vaccineService.GetAllVaccines()
    Return View(viewModel)
End Function

<HttpPost>
Function ReloadIndex(ByVal viewModel As AjaxVaccineFilterViewModel) As JsonResult
    Dim allVaccines As New List(Of Vaccine)
    allVaccines = _vaccineService.GetAllVaccines()
    'filter with client request (which filter?)
    Dim filteredVaccines As New List(Of Vaccine)
    If viewModel.Filter = "1" Then
       filteredVaccines = allVaccines.Where(Function(x) x.VFC.ToLower = "yes").ToList()
    ElseIf viewModel.Filter = "2" Then
       filteredVaccines = allVaccines.Where(Function(x) x.VFC.ToLower = "no").ToList()
    ElseIf viewModel.Filter = "3" Then
        filteredVaccines = allVaccines.Where(Function(x) x.Recommend.ToLower = "yes").ToList()
    ElseIf viewModel.Filter = "4" Then
         filteredVaccines = allVaccines.Where(Function(x) x.Recommend.ToLower = "no").ToList()
    ElseIf viewModel.Filter = "5" Then
         filteredVaccines = allVaccines.Where(Function(x) x.Active.ToLower = "yes").ToList()
    ElseIf viewModel.Filter = "6" Then
         filteredVaccines = allVaccines.Where(Function(x) x.Active.ToLower = "no").ToList()
    Else
         'should not reach this condition
    End If
    'update viewModel
    viewModel.Vaccines = filteredVaccines
    Return Json(viewModel, JsonRequestBehavior.AllowGet)
End Function

视图模型

Public Class AjaxVaccineFilterViewModel
    Public Property Vaccines As New List(Of Vaccine)
    Public Property Filter As String
End Class

DataTables 网站有一个示例,似乎是一个解决方案,但我无法获得我暗示要刷新的数据表。

【问题讨论】:

  • 你得到什么错误?
  • DataTables 警告:表 id=sample_4 - JSON 响应无效。有关此错误的更多信息,请参阅datatables.net/tn/1,这是在我的 .js 文件 $('#sample_4').DataTable().ajax.reload(); 成功后产生的结果;
  • 请在初始化数据表和重新加载的位置添加代码。谢谢
  • 我在控制器中添加了调用局部视图和httpget的视图。
  • 我没有看到任何数据表初始化代码。看起来您是在页面加载时手动创建表(然后可能是应用插件),但随后尝试使用数据表 API 进行过滤。对吗?

标签: asp.net-mvc vb.net jquery-plugins datatables


【解决方案1】:

试试这个...

$.ajax({
    url: app_base + 'Vaccine/ReloadIndex',
    type: 'POST',
    dataType: 'html',
    contentType: 'application/json; charset=utf-8',
    data: strung,
    success: function (data) {
        var vaccines = data.Vaccines,
            table = $('#sample_4').DataTable();

        table.destroy();

        try {
            oTable = $('#sample_4').DataTable({
                "aLengthMenu": [[15, 30, 60, 120, -1], [15, 30, 60, 120, "All"]],
                "bProcessing": true,
                responsive: false,
                "scrollX": true,
                "aaData": vaccines,
                "columns": [
                 {
                     vaccines: "VaccineId",
                     render: function (vaccines, type, Vaccine) {
                         return '<a class="btn-sm btn-primary" href="/Vaccine/Edit/' + Vaccine.VaccineId + '">Edit</a>';
                     }
                 },
                 {
                    vaccines: "VaccineAbbreviation",
                    render: function (vaccines, type, Vaccine) {
                        return Vaccine.VaccineAbbreviation;
                    }
                 }]
            });
        } catch (exception) {
            alert(exception, "Attention", "error");
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Error: " + xhr.status + " " + thrownError);
    }
});

【讨论】:

  • 我执行了您的建议并收到错误“表 id=sample_4 - 请求第 0 行第 1 列的未知参数 '1'。”除了datatables.net之外,你有没有可以指导我更详细的代码sn-p的参考?
  • 嗨,威廉,您即将解决我的问题。我的数据成功返回,我可以通过 Chrome>Sources 选项卡和断点看到它。我需要销毁当前表并创建一个新的数据表吗?
  • 嗨,是的,销毁数据表的实际实例,我在使用 AJAX 更新数据时使用了这种方式,因为重新加载对我不起作用。
  • 嗨威廉,成功后我的视图模型返回为:data = Object {Vaccines: Array(71), Filter: "5"} 如何引用 Vaccines 数组中的索引?另外,我正在尝试重建列。您会查看我更新的答案并提供建议吗?
  • 已更新问题,未更新答案。顺便说一句,我不再强烈键入我的表格并使用 ajax 加载 $(document).ready(function () { 和 "type": "get",
【解决方案2】:

在官方forum说:

$('#example').DataTable().ajax.reload();

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多