.NET 帮助

Jquery Datatable(开发人员的工作原理)

发布 2024年一月27日
分享:

数据展示是网络开发的一个重要方面,而在处理表格数据时,拥有一个交互式且功能丰富的表格至关重要。 jQuery DataTables 是一个功能强大的 JavaScript 库,可为创建动态和响应式表格提供高级功能。在本文中,我们将探讨如何将 jQuery DataTables 集成并用于 ASP.NET 网络应用程序,以增强表格数据的显示效果。

如何在 ASP.NET Web 应用程序中使用 jQuery DataTables?

1.创建或打开网络应用程序。

2.安装 Entity Framework 软件包

3.添加模型、数据库上下文和控制器。

4.添加数据库连接字符串并设置配置。

5.添加迁移和更新数据库。

6.添加 jQuery DataTables 客户端库。

7.添加 HTML 表格和 JavaScript 代码。

8.构建并运行应用程序。

9.使用以下工具将数据导出到 Excel IronXL.

什么是 jQuery DataTables?

jQuery DataTables是一款轻量级、灵活且功能丰富的jQuery插件,用于处理表格数据。它提供排序、搜索、分页等多种功能,是以用户友好的方式展示大型数据集的理想选择。

客户端处理

在客户端处理中,浏览器有权在本地处理数据集。jQuery DataTables 通过其强大的功能,可以直接在用户浏览器中对数据进行动态交互和操作。虽然这种方法可以无缝处理较小的数据集,但在处理大型数据集时可能会面临潜在的性能瓶颈和资源消耗增加的挑战。

在本文中,我们将探讨 ASP.NET Razor Page 应用程序中的客户端处理,强调它为较小数据集提供的优势,并深入探讨潜在的注意事项和优化方法,以确保流畅、响应迅速的用户体验。

在 ASP.NET 网络应用程序中开始使用 jQuery DataTables

本文将使用以 .NET Framework 4.8 为目标的 ASP.NET Razor 页面 Web 应用程序。您可以根据需要使用 Blazor、MVC 或 Web 窗体。

本文将使用代码优先方法。您可以根据自己的偏好使用数据库优先方法。要使用代码优先方法,我们需要安装以下软件包。

1.Microsoft.EntityFrameworkCore

2.Microsoft.EntityFrameworkCore.Design

3.Microsoft.EntityFrameworkCore.SqlServer

4.Microsoft.EntityFrameworkCore.Tools

使用 NuGet 软件包管理器控制台中的 "Install-Package "命令安装上述软件包,或从 NuGet 软件包管理器解决方案中搜索安装。

让我们在 Program.cs 中添加模型类、ApplicationDBContext 类、控制器、连接字符串和服务配置,从而建立我们的项目。

添加模型类

我在这个示例中使用了 Employee 模型类,你可以根据自己的需要使用它。

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public string PhoneNumber { get; set; } = string.Empty;
    public string Gender { get; set; } = string.Empty;
    public string Designation { get; set; } = string.Empty;
}
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public string PhoneNumber { get; set; } = string.Empty;
    public string Gender { get; set; } = string.Empty;
    public string Designation { get; set; } = string.Empty;
}
Public Class Employee
	Public Property Id() As Integer
	Public Property FirstName() As String = String.Empty
	Public Property LastName() As String = String.Empty
	Public Property Email() As String = String.Empty
	Public Property PhoneNumber() As String = String.Empty
	Public Property Gender() As String = String.Empty
	Public Property Designation() As String = String.Empty
End Class
VB   C#

添加 ApplicationDbContext 类

我们需要添加 "ApplicationDbContext "类来设置实体框架。

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
}
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
}
Public Class ApplicationDbContext
	Inherits DbContext

	Public Sub New(ByVal options As DbContextOptions(Of ApplicationDbContext))
		MyBase.New(options)
	End Sub

	Public Property Employees() As DbSet(Of Employee)
End Class
VB   C#

添加员工控制器

添加 EmployeeController 以创建端点。

[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public EmployeeController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult GetEmployees()
    {
        try
        {
            var employeeData = _context.Employees.ToList();
            var jsonData = new { data = employeeData };
            return Ok(jsonData);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public EmployeeController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult GetEmployees()
    {
        try
        {
            var employeeData = _context.Employees.ToList();
            var jsonData = new { data = employeeData };
            return Ok(jsonData);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
<Route("api/[controller]")>
<ApiController>
Public Class EmployeeController
	Inherits ControllerBase

	Private ReadOnly _context As ApplicationDbContext

	Public Sub New(ByVal context As ApplicationDbContext)
		_context = context
	End Sub

	<HttpGet>
	Public Function GetEmployees() As IActionResult
		Try
			Dim employeeData = _context.Employees.ToList()
			Dim jsonData = New With {Key .data = employeeData}
			Return Ok(jsonData)
		Catch ex As Exception
			Throw
		End Try
	End Function
End Class
VB   C#

在这里,我们使用了 HttpGet 方法,因为我们将在客户端从服务器检索完整的数据,并在客户端实施分页、搜索和排序。我们将返回一个在客户端渲染的 JSON 数组。

添加连接字符串

在 appsettings.json 文件中添加以下连接字符串。

"ConnectionStrings": {
  "EmployeeDB": "Server=localserver\\SQLEXPRESS;Database=EmployeeDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
}

在 Program.cs 类中的 webApplication.CreateBuilder' 下添加以下一行()连接 SQL Server 的 行。

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeDB"));
});
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeDB"));
});
builder.Services.AddDbContext(Of ApplicationDbContext)(Sub(options)
	options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeDB"))
End Sub)
VB   C#

运行迁移

下一步是运行迁移,因为我们使用的是 "代码优先 "方法。在软件包管理器控制台运行以下命令。

Add-Migration init

该命令将创建迁移。现在,运行以下命令将迁移应用到数据库。

update-database

现在,我们的项目已经设置完毕,数据库也已准备就绪,只需添加 jQuery 库和 HTML 表格,就可以使用我们的用户界面了。在本例中,我们使用 SQL Server 作为数据源,但您也可以使用任何其他数据库。

添加 jQuery DataTables 库

我们需要在项目中添加 jQuery DataTables 库,它是 jQuery JavaScript 库的表格增强插件。我们可以通过右键单击项目,选择 "添加",然后选择 "添加客户端库 "来添加它。这时会出现一个小窗口,我们可以搜索 "jquery datatables "并安装它,如下图所示:

添加 jQuery DataTables 库

添加 HTML 表格

让我们添加一个 HTML 表格,表格主体为空。我们将在设置 jQuery DataTable 时添加所需的列标题。在 Index.cshtml 文件中添加以下代码。

@page
@model IndexModel
@{
    ViewData ["Title"] = "Home page";
}
<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="employeeDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
        </table>
    </div>
</div>
@section Scripts
{
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/js/EmployeeDatatable.js"></script>
}

我们需要在 wwwroot/Js 文件夹中添加 EmployeeDatatable.js 文件。在该文件中,我们将调用 Ajax 和 jQuery DataTable 的高级功能,如过滤、分页、搜索、排序等。

创建 EmployeeDatable.js 文件

wwwroot/Js 文件夹中创建 EmployeeDatatable.js 文件。添加以下代码。

$(document).ready(function () {
    $("#employeeDatatable").DataTable({
        "processing": true,
        "serverSide": false,
        "filter": true,
        "ajax": {
            "url": "/api/Employee",
            "type": "GET",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0],
            "visible": false,
            "searchable": false
        }],
        "columns": [
            { "data": "id", "title": "Employee ID", "name": "Employee ID", "autoWidth": true },
            { "data": "firstName", "title": "First Name", "name": "First Name", "autoWidth": true },
            { "data": "lastName", "title": "Last Name", "name": "Last Name", "autoWidth": true },
            { "data": "email", "title": "Email", "name": "Email", "autoWidth": true },
            { "data": "phoneNumber", "title": "Phone Number", "name": "Phone Number", "autoWidth": true },
            { "data": "gender", "title": "Gender", "name": "Gender", "autoWidth": true },
            { "data": "designation", "title": "Designation", "name": "Designation", "autoWidth": true }
        ]
    });
});
JAVASCRIPT

我们使用了功能丰富的 jQuery DataTables 库。这个功能强大的 jQuery 插件使我们能够以最小的代价在客户端实现高级功能。

现在,构建并运行此应用程序。

输出

我们可以看到,在 ASP.NET 中 jQuery 的帮助下,我们已经准备好了一个交互性很强的用户界面。显示的数据如下

jQuery DataTables 输出

现在,分页是在客户端实现的,因此完整的数据将从服务器发送,如下图所示:

分页

输出用户界面

我们可以搜索、排序和更改页面,所有操作都将在客户端完成,如下图所示:

输出用户界面

IronXL 简介

IronXL 是一个可让你在.NET 应用程序中处理 Excel 文件的库。它可以创建、读取、编辑和保存各种格式的 Excel 文档,如 XLS、XLSX、CSV 和 TSV。它不需要安装 Microsoft Office 或 Excel Interop。它支持 .NET 5、Core、Framework 和 Azure。

我们经常需要将数据导出为 Excel 或 CSV 文件。在这种情况下,IronXL 是最佳选择。现在,我们将编写将数据导出到 Excel 文件的代码。

安装 IronXL

在软件包管理器控制台输入以下命令,在项目中安装 IronXL 库。

Install-Package IronXL.Excel

这将在我们的项目中安装 IronXL 和所需的依赖项。您也可以直接从 下载链接。

将数据导出到 Excel

让我们编写代码,将员工列表转换成 Excel 文件。

public void ExportToExcel(List<Employee> employeeList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = wb.DefaultWorkSheet;

    // Add Header Row
    ws ["A1"].Value = "Employee ID";
    ws ["B1"].Value = "First Name";
    ws ["C1"].Value = "Last Name";
    ws ["D1"].Value = "Designation";
    ws ["E1"].Value = "Gender";
    ws ["F1"].Value = "Phone Number";
    ws ["G1"].Value = "Email";

    int rowCount = 2;

    // Add Data
    foreach (Employee employee in employeeList)
    {
        ws ["A" + rowCount].Value = employee.Id.ToString();
        ws ["B" + rowCount].Value = employee.FirstName;
        ws ["C" + rowCount].Value = employee.LastName;
        ws ["D" + rowCount].Value = employee.Designation;
        ws ["E" + rowCount].Value = employee.Gender;
        ws ["F" + rowCount].Value = employee.PhoneNumber;
        ws ["G" + rowCount].Value = employee.Email;

        rowCount++;
    }

    wb.SaveAs("Employee.xlsx");
}
public void ExportToExcel(List<Employee> employeeList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = wb.DefaultWorkSheet;

    // Add Header Row
    ws ["A1"].Value = "Employee ID";
    ws ["B1"].Value = "First Name";
    ws ["C1"].Value = "Last Name";
    ws ["D1"].Value = "Designation";
    ws ["E1"].Value = "Gender";
    ws ["F1"].Value = "Phone Number";
    ws ["G1"].Value = "Email";

    int rowCount = 2;

    // Add Data
    foreach (Employee employee in employeeList)
    {
        ws ["A" + rowCount].Value = employee.Id.ToString();
        ws ["B" + rowCount].Value = employee.FirstName;
        ws ["C" + rowCount].Value = employee.LastName;
        ws ["D" + rowCount].Value = employee.Designation;
        ws ["E" + rowCount].Value = employee.Gender;
        ws ["F" + rowCount].Value = employee.PhoneNumber;
        ws ["G" + rowCount].Value = employee.Email;

        rowCount++;
    }

    wb.SaveAs("Employee.xlsx");
}
Public Sub ExportToExcel(ByVal employeeList As List(Of Employee))
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	Dim ws As WorkSheet = wb.DefaultWorkSheet

	' Add Header Row
	ws ("A1").Value = "Employee ID"
	ws ("B1").Value = "First Name"
	ws ("C1").Value = "Last Name"
	ws ("D1").Value = "Designation"
	ws ("E1").Value = "Gender"
	ws ("F1").Value = "Phone Number"
	ws ("G1").Value = "Email"

	Dim rowCount As Integer = 2

	' Add Data
	For Each employee As Employee In employeeList
		ws ("A" & rowCount).Value = employee.Id.ToString()
		ws ("B" & rowCount).Value = employee.FirstName
		ws ("C" & rowCount).Value = employee.LastName
		ws ("D" & rowCount).Value = employee.Designation
		ws ("E" & rowCount).Value = employee.Gender
		ws ("F" & rowCount).Value = employee.PhoneNumber
		ws ("G" & rowCount).Value = employee.Email

		rowCount += 1
	Next employee

	wb.SaveAs("Employee.xlsx")
End Sub
VB   C#

我们以简单易行的方式从列表中创建了 Excel 文件。

输出 Excel 文件

IronXL 提供全面的 教程, 代码示例文献资料 帮助您以最佳方式利用其全面的应用程序接口。

结论

总之,jQuery DataTables 已成为 ASP.NET 网络应用程序中转换表格数据显示方式的强大工具。其轻量级但功能丰富的特性有助于创建交互式表格,将排序、搜索和分页功能发挥到极致。我们探索了客户端处理的细微差别,利用浏览器的功能来处理较小的数据集,同时也认识到了处理较大数据量时可能遇到的挑战。关于设置 ASP.NET Razor Page 应用程序和集成 jQuery DataTables 的分步指南为开发人员提供了实用的见解。此外,IronXL 作为 Excel 相关任务的无缝解决方案,为工具包增加了一个有价值的层,实现了高效的数据导出。有了这些工具,开发人员就能以引人注目和易于访问的方式展示数据,从而提升用户体验。

IronXL 提供多种许可选项,具体取决于开发人员、项目和再分发需求的数量。许可证是永久性的,包括免费支持和更新。

< 前一页
C#数组排序(开发人员如何使用)
下一步 >
C# 计时器(它是如何为开发人员工作的)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >