【问题标题】:How to add pagination in ASP.NET Core MVC, on dynamically created table within AJAX call如何在 ASP.NET Core MVC 中添加分页,在 AJAX 调用中动态创建的表上
【发布时间】:2021-07-04 15:58:27
【问题描述】:

cshtml:

<!--Grid view details-->
<div class="divGrid" id="divGridSales" style="display:none;">
    <div class="table-responsive" id="ItemTableDiv" style="float: none;">
        <div class="table-responsive">
            <table class="table tblView" id="tblViewPartDetails">
                <thead id="itemTblHeaderColumns">
                </thead>
                <tbody id="ItemConfigGrid">
                </tbody>
            </table>
        </div>
    </div>
</div>

在下拉更改事件中,我正在动态创建表格,如下所示,

$("#ddlCountry").change(function () {
    $("#divGridSales").css({ display: "none" });

    var id = {};
    id.pLobID = $('#ddlLOB').val();
    id.pCountryID = $('#ddlCountry').val();

    if (id.pCountryID > 0) {
        $.ajax({
            type: "GET",
            url: "../Controller/Method",
            data: id,
            success: function (data) {
                if (data != null) {
                    debugger;
                    if (data != null && data.length > 0) {
                        var tableHeader = $('#itemTblHeaderColumns')
                        $("#itemTblHeaderColumns tr").remove();
                        var trHeader = $('<tr /> ').appendTo(tableHeader);
                        /////This is used to bind columns
                        trHeader.append('<th class="trheaderTable" style="width: 12%;"> Part Number </th>');//PartNumber
                        trHeader.append('<th class="trheaderTable" style="width: 5%;"> Action </th>');//Action
                        ///This is used to bind rows
                        var tbody = $('#ItemConfigGrid');
                        $("#ItemConfigGrid tr").remove();
                        for (var iRow = 0; iRow < data.length; iRow++) {
                            var tr = $('<tr /> ').appendTo(tbody);
                            tr.append('<td>' + data[iRow].partNumber + '</td>');
                            tr.append('<td><a href="#" id="hlinkView" class="ti-eye" data-toggle="modal" data-target="#exampleModal" onclick="getPartDetailsByPartNumber(' + data[iRow].partNumber + ')"></a></td>');
                        }
                        $('#tblViewPartDetails').DataTable();
                        $("#divGridSales").css({ display: "block" });
                   }
                    else {
                        alert('Something went to wrong!');
                    }
                }
            }
        });
    }
});

tblViewPartDetails 桌子上我必须添加分页

注意:我试过DataTable插件,第一次按要求显示数据。但是下一次,当下拉列表更改时,所有数据都会显示(分页不起作用)。

【问题讨论】:

  • 我没有看到你的代码有任何问题,你能解释一下你所面临的问题吗?我也没有看到任何与分页相关的请求参数,您如何确定服务器端的当前页数?
  • @SowmyadharGourishetty 我需要为这个动态添加的 HTML 表格添加分页,我已经尝试过 DataTable 插件,但没有像 Note 中提到的那样工作。
  • 我了解到您想要实现分页。您现在拥有的代码将按预期工作,但唯一的问题是您如何处理需要从服务器发送的记录数。例如:First Load,Current Page 为 1,然后加载前 1 条记录,Second Page,Current Page 为 2,则需要跳过前 10 条记录,获取后 10 条记录。您也可以对 DataTable 执行相同操作,只需使用 $('#myTable').dataTable().clear(); 清除 DataTable
  • @SowmyadharGourishetty 感谢您的回复,但我的实际要求是我必须在客户端为整个数据添加分页,它将显示在 Dropdown 的更改事件中。第一次使用 DataTable 它可以按要求正常工作,但是当我更改 Drop down 时,它会显示所有带有分页的数据,但以前的记录计数也没有清除搜索文本框。当我们搜索新文本时,它会按要求工作。我们可以在 ASP Dot Net Core 中添加类似 Web 网格的功能吗?
  • 您能否发布您为 DataTable 尝试的实现?

标签: c# ajax pagination asp.net-core-mvc


【解决方案1】:

这是一个完整的工作演示,您可以关注:

型号:

public class Country
{
    public int pCountryID { get; set; }
    public int pLobID { get; set; }
}

查看:

<select id="ddlCountry">
    <option value="0">Select a Value</option>
    <option value="1">Shanghai</option>
    <option value="2">Nanjing</option>
    <option value="3">Wuhan</option>
</select>
<div class="divGrid" id="divGridSales" style="display:none;">
    <div class="table-responsive" id="ItemTableDiv" style="float: none;">
        <div class="table-responsive">
            <table class="table tblView" id="tblViewPartDetails">
                <thead>
                   
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

JS:

@section Scripts
{
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
    <script>
        $("#ddlCountry").change(function () {
            $("#divGridSales").css({ display: "none" });
            var id = {};
            id.pLobID = $('#ddlLOB').val();
            id.pCountryID = $('#ddlCountry').val();
            var columns = [];
            if (id.pCountryID > 0) {
                $.ajax({
                    type: "GET",
                    url: "/Home/Test",
                    data: id,
                    success: function (data) {
                        console.log(data);
                        columnNames = Object.keys(data[0]);
                        console.log(columnNames);
                        for (var i in columnNames) {
                            columns.push({
                                data: columnNames[i],
                                title: columnNames[i]
                            });
                        }
                        $("#divGridSales").css({ display: "block" });
                        $('#tblViewPartDetails').DataTable({
                            "processing": true, // for show progress bar
                            "serverSide": false, // for process server side
                            "filter": true, // this is for disable filter (search box)
                            "orderMulti": false, // for disable multiple column at once
                            "bDestroy": true,   //for reinitialize the datatable
                            "data": data,
                            "columns": columns
                        });
                    }
                });
            }
        });
    </script>
}

控制器:

public class HomeController : Controller
{
    List<Country> countries = new List<Country>()
    {
        new Country (){pLobID=1,pCountryID=1},
        //more hard coded data...      
        new Country (){pLobID=313,pCountryID=3},       
    };       
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }
    public IActionResult Test(Country model) 
    {
        var data = countries.Where(a => a.pCountryID == model.pCountryID)
                            .ToList();
        return Json(data);
    }
}

结果:

更新:

您需要在columns 中添加一个新项目才能将按钮放在此列中。然后记得在Datatable中使用columnDefs方法添加这个按钮:

<script>
    $("#ddlCountry").change(function () {
        $("#divGridSales").css({ display: "none" });
        var id = {};
        id.pLobID = $('#ddlLOB').val();
        id.pCountryID = $('#ddlCountry').val();
        var columns = [];
        if (id.pCountryID > 0) {
            $.ajax({
                type: "GET",
                url: "/Home/Test",
                data: id,
                success: function (data) {
                    columnNames = Object.keys(data[0]);
                    console.log(columnNames);
                    for (var i in columnNames) {
                        columns.push({
                            data: columnNames[i],
                            title: columnNames[i]
                        });
                    }
                    //add this...
                    columns.push({
                        data: "Operation",
                        title: "Operation"
                    })
                    $("#divGridSales").css({ display: "block" });
                    $('#tblViewPartDetails').DataTable({
                        "processing": true, // for show progress bar
                        "serverSide": false, // for process server side
                        "filter": true, // this is for disable filter (search box)
                        "orderMulti": false, // for disable multiple column at once
                        "bDestroy": true,   //for reinitialize the datatable
                        "data": data,
                        "columns": columns,
                        "columnDefs": [
                            {
                                // The `data` parameter refers to the data for the cell.
                                // The `rows`argument is an object representing all the data for the current row.
                                "render": function (data, type, row) {
                                    return "<button class='btn btn-danger btn-delete' onclick='Delete(" + row.pLobID + ")'>Delete</button>||<button class='btn btn-danger btn-delete' onclick='Edit(" + row.pLobID + ")'>Edit</button>";
                                },
                                "targets": -1  // -1 is the last column, 0 the first, 1 the second, etc.
                            }
                        ]
                        
                    });
                }
            });
        }
    });
    function Delete(data) {
        alert(data);
    };
    function Edit(data) {
        alert(data);
    }
</script>

如果要隐藏列,可以在columnDefs中添加以下代码:

"columnDefs": [
    {
        // The `data` parameter refers to the data for the cell.
        // The `rows`argument is an object representing all the data for the current row.
        "render": function (data, type, row) {
            return "<button class='btn btn-danger btn-delete' onclick='Delete(" + row.pLobID + ")'>Delete</button>||<button class='btn btn-danger btn-delete' onclick='Edit(" + row.pLobID + ")'>Edit</button>";
        },
        "targets": -1  // -1 is the last column, 0 the first, 1 the second, etc.
    },

      //add here.....
    {
        "targets": [0],//0 the first, 1 the second, etc.
        "visible": false
    }
]

【讨论】:

  • 按照您的建议尝试,但出现如下错误,而“columns.push({" Error: "Uncaught ReferenceError: columns is not defined"
  • 嗨@MTaj,​​您似乎没有定义列,请仔细检查我的代码。你可能会错过var columns = [];
  • 非常感谢您的宝贵帮助,现在工作正常。我们如何像上面的代码一样添加操作列或如何显示/隐藏列,还有一个帮助。截至目前,所有列都显示为从 DB 提供给我们的。根据我的要求,我正在创建动态 HTML(如上面的代码所示)表,其中一个操作列具有超链接,用于在弹出窗口中显示详细信息。我们可以通过 Datatable 插件来实现吗?
  • 嗨@M Taj,如果我的回答能帮助您解决问题,您能接受吗?请参阅:How to accept as answer.Thanks。
  • 主要问题仍然没有解决@Rena,因为我正在为如何实现创建动态表,我没有得到。
猜你喜欢
  • 2014-08-05
  • 1970-01-01
  • 2016-08-12
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多