65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET8 使用 DataTables.net – 第8部分 – 选择行

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2024 年 7 月 30 日

CPOL

3分钟阅读

viewsIcon

3984

downloadIcon

187

在 ASP.NET 8 MVC 应用程序中使用 jQuery DataTables.net 组件的实用指南。

1 ASP.NET8 使用 jQuery DataTables.net

我正在评估 jQuery DataTables.net 组件 [1] 在 ASP.NET8 项目中的使用,并创建了几个原型(概念验证)应用程序,这些应用程序将在这些文章中介绍。

1.1 本系列文章

本系列文章包括:

  • ASP.NET8 使用 DataTables.net – 第1部分 – 基础
  • ASP.NET8 使用 DataTables.net – 第2部分 – 操作按钮
  • ASP.NET8 使用 DataTables.net – 第3部分 – 状态保存
  • ASP.NET8 使用 DataTables.net – 第4部分 – 多语言
  • ASP.NET8 使用 DataTables.net – 第5部分 – 在 AJAX 中传递附加参数
  • ASP.NET8 使用 DataTables.net – 第6部分 – 在 AJAX 中返回附加参数
  • ASP.NET8 使用 DataTables.net – 第7部分 – 常规按钮
  • ASP.NET8 使用 DataTables.net – 第8部分 – 选择行
  • ASP.NET8 使用 DataTables.net – 第9部分 – 高级筛选器

2 最终结果

本文的目标是创建一个概念验证应用程序,演示 DataTables.net 组件的表格中行的选择。 让我们展示本文的结果。

关键是,DataTables.net 组件允许您选择表格中的行,并将选择信息传递给其他操作进行处理。

我们在这里展示通用的按钮:全选/取消全选

然后我们展示了对选定行的 2 个操作,第一个只是显示选定行的 ID,第二个是将选定行的 ID 列表传递给某个操作以进行处理。

3 下载 DataTables 组件

站点 [1] 描述了几种获取组件的方法,包括 CDN 和 NuGet 包。 并非所有方法都对我有效,所以我发现对我来说最好的方法是直接从站点下载它并直接将其部署在项目中。

您可以查看 datatables.js 标头以查看您系统上的版本。

//datatables.js

/*
 * This combined file was created by the DataTables downloader builder:
 *   https://datatables.net.cn/download
 *
 * To rebuild or modify this file with the latest versions of the included
 * software please visit:
 *   https://datatables.net.cn/download/#bs5/jszip-3.10.1/pdfmake-0.2.7/dt-2.0.8/b-3.0.2/b-colvis-3.0.2/b-html5-3.0.2/b-print-3.0.2/sl-2.0.3/sr-1.4.1
 *
 * Included libraries:
 *   JSZip 3.10.1, pdfmake 0.2.7, DataTables 2.0.8, Buttons 3.0.2, Column visibility 3.0.2, HTML5 export 3.0.2, Print view 3.0.2, Select 2.0.3, StateRestore 1.4.1
 */
 

4 JavaScript 实用程序

对于此示例,我们需要一些 JavaScript 辅助函数。 它们在这里。

//util1.js

/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the parameters to add to the url
* @param {string} [method=post] the method to use on the form
*
* Warning: This solution is limited and does not handle arrays or nested objects inside of a form.
*/

function postToUrl1(path, params, method = 'post') {

    // The rest of this code assumes you are not using a library.
    // It can be made less verbose if you use one.
    const form = document.createElement('form');
    form.method = method;
    form.action = path;

    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

//function is used when we need to extract a list of a given property
//extract values from an array of objects based on a specific key
function PluckUtil1(array, key) {
    return array.map(function (obj) {
        return obj[key];
    });
}

5 客户端 DataTables.net 组件

在这里,我将只展示使用 DataTables 组件的 ASP.NET 视图的样子。

<!-- Employees.cshtml -->
<partial name="_LoadingDatatablesJsAndCss" />

@{
    <div class="text-center">
        <h3 class="display-4">Employees table</h3>
    </div>

    <!-- Here is our table HTML element defined. JavaScript library Datatables
    will do all the magic to turn it into interactive component -->
    <table id="EmployeesTable01" class="table table-striped table-bordered ">
    </table>
}

<script src="~/lib/JSUtil/util1.js" asp-append-version="true"></script>

<script>
    // Datatables script initialization=========================================
    // we used defer attribute on jQuery so it might not be available at this point
    // so we go for vanilla JS event

    document.addEventListener("DOMContentLoaded", InitializeDatatable);

    function InitializeDatatable() {
        let myTable = new DataTable("#EmployeesTable01", {
            //processing-Feature control the processing indicator.
            processing: true,
            //paging-Enable or disable table pagination.
            paging: true,
            //info-Feature control table information display field
            info: true,
            //ordering-Feature control ordering (sorting) abilities in DataTables.
            ordering: true,
            //searching-Feature control search (filtering) abilities
            searching: true,
            //search.return-Enable / disable DataTables' search on return.
            search: {
                return: true
            },
            //autoWidth-Feature control DataTables' smart column width handling.
            autoWidth: true,
            //lengthMenu-Change the options in the page length select list.
            lengthMenu: [10, 15, 25, 50, 100],
            //pageLength-Change the initial page length (number of rows per page)
            pageLength: 10,

            //order-Initial order (sort) to apply to the table.
            order: [[2, 'asc']],

            //serverSide-Feature control DataTables' server-side processing mode.
            serverSide: true,

            //Select extension
            select: {
                style: 'os',
                selector: 'td:first-child',
                headerCheckbox: 'select-page'
            },

            //Load data for the table's content from an Ajax source.
            ajax: {
                "url": "@Url.Action("EmployeesDT", "Home")",
                "type": "POST",
                "datatype": "json"
            },

            //Set column specific initialization properties
            columns: [
                //name-Set a descriptive name for a column
                //data-Set the data source for the column from the rows data object / array
                //title-Set the column title
                //orderable-Enable or disable ordering on this column
                //searchable-Enable or disable search on the data in this column
                //type-Set the column type - used for filtering and sorting string processing
                //visible-Enable or disable the display of this column.
                //width-Column width assignment.
                //render-Render (process) the data for use in the table.
                //className-Class to assign to each cell in the column.

                {   //0
                    name: 'selectCheckbox',
                    //data: 'selectCheckbox',
                    //title: "",
                    orderable: false,
                    //searchable: false,
                    //type: 'num',
                    //visible: true,
                    render: DataTable.render.select(),
                    width: "50px",
                },
                {   //1
                    name: 'id',
                    data: 'id',
                    title: "Employee Id",
                    orderable: false,
                    searchable: false,
                    type: 'num',
                    visible: true
                },
                {
                    //2
                    name: 'givenName',
                    data: "givenName",
                    title: "Given Name",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //3
                    name: 'familyName',
                    data: "familyName",
                    title: "Family Name",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //4
                    name: 'town',
                    data: "town",
                    title: "Town",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //5
                    name: 'country',
                    data: "country",
                    title: "Country",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true,
                    width: "150px",
                    className: 'text-center '
                },
                {
                    //6
                    name: 'email',
                    data: "email",
                    title: "Email",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //7
                    name: 'phoneNo',
                    data: "phoneNo",
                    title: "Phone Number",
                    orderable: false,
                    searchable: true,
                    type: 'string',
                    visible: true
                }
            ],
            layout: {
                top1Start: {
                    buttons:
                        [
                            'selectNone',
                            'selectAll',
                            {
                                extend: 'selected',
                                text: 'Show selected data',
                                action: function () {
                                    let myRows = myTable.rows({ selected: true });
                                    let data = myRows.data();
                                    let ids = PluckUtil1(data, 'id');
                                    let idsString = ids.toArray().join(',');

                                    alert('Selected:' + idsString);
                                }
                            },
                            {
                                text: 'Deselect all2',
                                action: function () {
                                    let myRows = myTable.rows({ selected: true });
                                    myRows.deselect();
                                }
                            },
                            {
                                extend: 'selected',
                                text: 'Action with selected data',
                                action: function () {
                                    let myRows = myTable.rows({ selected: true });
                                    let data = myRows.data();
                                    let ids = PluckUtil1(data, 'id');
                                    let idsString = ids.toArray().join(',');

                                    //let SelectedEmployeesUrl = "@Url.Action("SelectedEmployees", "Home")" +
                                    //    "?SelectedIds=" + idsString;
                                    //redirect to another page
                                    //window.location.replace(SelectedEmployeesUrl);

                                    postToUrl1("@Url.Action("SelectedEmployees", "Home")", { SelectedIds: idsString });
                                }
                            },
                        ]
                }
            }
        });
    }

</script>

请注意,我们使用 layout 属性在此示例中定义所有按钮。

有关这些属性的更多信息,请参阅 [1] 中的手册。这里的应用程序只是 ASP.NET 环境的一个概念验证。

6 ASP.NET 后端处理

所以,我们现在在 C#/.NET 部分,编写我们的 ASP.NET 代码。 这是接收和处理 ID 列表的部分。

//SelectedEmployeesVM.cs
namespace Example08.Models.Home
{
    public class SelectedEmployeesVM
    {
        //model
        public string? SelectedIds { get; set; } = null;
        //view model
        public List<string>? SelectedIdsList { get; set; } = null;
    }
}

//HomeController.cs
public IActionResult SelectedEmployees(SelectedEmployeesVM model)
{
    model.SelectedIds = model.SelectedIds?.Trim();
    if (model.SelectedIds != null)
    {
        string[] strings = model.SelectedIds.Split(',');
        model.SelectedIdsList = new List<string>(strings);
    }
    return View(model);
}

7 结论

可以下载完整的示例代码项目。

8 参考

[1] https://datatables.net.cn/

[21] ASP.NET8 使用 DataTables.net – 第1部分 – 基础
https://codeproject.org.cn/Articles/5385033/ASP-NET-8-Using-DataTables-net-Part1-Foundation

[22] ASP.NET8 使用 DataTables.net – 第2部分 – 操作按钮
https://codeproject.org.cn/Articles/5385098/ASP-NET8-using-DataTables-net-Part2-Action-buttons

[23] ASP.NET8 使用 DataTables.net – 第3部分 – 状态保存
https://codeproject.org.cn/Articles/5385308/ASP-NET8-using-DataTables-net-Part3-State-saving

[24] ASP.NET8 使用 DataTables.net – 第4部分 – 多语言
https://codeproject.org.cn/Articles/5385407/ASP-NET8-using-DataTables-net-Part4-Multilingual

[25] ASP.NET8 使用 DataTables.net – 第5部分 – 在 AJAX 中传递附加参数
https://codeproject.org.cn/Articles/5385575/ASP-NET8-using-DataTables-net-Part5-Passing-additi

[26] ASP.NET8 使用 DataTables.net – 第6部分 – 在 AJAX 中返回附加参数
https://codeproject.org.cn/Articles/5385692/ASP-NET8-using-DataTables-net-Part6-Returning-addi

[27] ASP.NET8 使用 DataTables.net – 第7部分 – 常规按钮
https://codeproject.org.cn/Articles/5385828/ASP-NET8-using-DataTables-net-Part7-Buttons-regula

[28] ASP.NET8 使用 DataTables.net – 第8部分 – 选择行
https://codeproject.org.cn/Articles/5386103/ASP-NET8-using-DataTables-net-Part8-Select-rows

[29] ASP.NET8 使用 DataTables.net – 第9部分 – 高级筛选器
https://codeproject.org.cn/Articles/5386263/ASP-NET8-using-DataTables-net-Part9-Advanced-Filte

 

© . All rights reserved.