在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
数据展示是网络开发的一个重要方面,在处理表格数据时,拥有一个交互式且功能丰富的表格至关重要。 jQuery DataTables 是一个强大的 JavaScript 库,它为创建动态和响应式表格提供了高级功能。 在这篇文章中,我们将探讨如何在ASP.NET Web 应用程序中集成和使用 jQuery DataTables,以增强表格式数据的呈现。
创建或打开网络应用程序。
安装 Entity Framework 软件包。
添加模型、数据库上下文和控制器。
添加数据库连接字符串并设置配置。
添加迁移和更新数据库。
添加 jQuery DataTables 客户端库。
添加 HTML 表格和 JavaScript 代码。
构建并运行应用程序。
jQuery DataTables 是一款轻量级、灵活且功能丰富的 jQuery 插件,用于处理表格数据。 它提供了多种功能,如排序、搜索、分页等,是以用户友好的方式展示大型数据集的理想选择。
在客户端处理中,浏览器有权在本地处理数据集。 jQuery DataTables 通过其强大的功能,可以直接在用户浏览器中对数据进行动态交互和操作。 虽然这种方法在处理较小的数据集时可以天衣无缝,但在处理大数据集时可能会面临潜在的性能瓶颈和资源消耗增加的挑战。
在本文中,我们将探讨 ASP.NET Razor Page 应用程序中的客户端处理,强调它为较小数据集提供的优势,并深入探讨潜在的注意事项和优化方法,以确保流畅、响应迅速的用户体验。
本文将使用以 .NET Framework 4.8 为目标的 ASP.NET Razor 页面 Web 应用程序。您可以根据需要使用 Blazor、MVC 或 Web 窗体。
本文将采用代码优先法。 您可以根据自己的偏好使用 "数据库优先法"。 我们需要安装以下软件包,以便使用代码优先方法。
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
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
我们需要添加ApplicationDbContext
类来设置Entity Framework。
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
添加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
在这里,我们使用HttpGet
方法,因为我们将在客户端从服务器检索完整数据,并在客户端实现分页、搜索和排序。我们返回一个将在客户端渲染的JSON数组。
在 appsettings.json 文件中添加以下连接字符串。
"ConnectionStrings": {
"EmployeeDB": "Server=localserver\\SQLEXPRESS;Database=EmployeeDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
}
在webApplication.CreateBuilder()
行下的 Program.cs 类中添加以下代码行以连接 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)
下一步是运行迁移,因为我们使用的是代码优先方法。 在软件包管理器控制台中运行以下命令。
Add-Migration init
Add-Migration init
此命令将创建迁移。 现在,运行以下命令将此迁移应用到数据库。
update-database
update-database
现在,我们的项目已经完成,数据库也已准备就绪,我们只需添加 jQuery 库和 HTML 表格,就可以使用我们的用户界面了。 在本示例中,我们使用 SQL Server 作为数据源,但您也可以使用任何其他数据库。
我们需要在项目中添加 jQuery DataTables 库,它是 jQuery JavaScript 库的表格增强插件。 我们可以通过右键单击项目,选择 "添加",然后选择 "添加客户端库 "来添加它。 这时会出现一个小窗口,我们可以在其中搜索 "jquery datatables "并安装,如下图所示:
让我们添加一个 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>
}
我们需要将 EmployeeDatatable.js 文件添加到 wwwroot/Js
文件夹中。 在本文件中,我们将使用 Ajax 调用和 jQuery DataTable 的高级功能,如过滤、分页、搜索、排序等。
在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 的帮助下,我们已经准备好了一个交互性很强的用户界面。 显示的数据如下:
现在,分页是在客户端实现的,因此完整的数据是从服务器发送的,如下图所示:
我们可以搜索、排序和更改页面,所有操作都将在客户端完成,如下图所示:
IronXL for .NET Excel 文件操作 是一个库,允许您在 .NET 应用程序中处理 Excel 文件。 它可以创建、读取、编辑和保存各种格式的 Excel 文档,如 XLS、XLSX、CSV 和 TSV。它不需要安装 Microsoft Office 或 Excel Interop。 它支持 .NET 5、Core、Framework 和 Azure。
我们经常需要将数据导出为 Excel 或 CSV 文件。 在这种情况下,IronXL 是最佳选择。 现在,我们将编写代码,将数据导出到 Excel 文件中。
在软件包管理器控制台中输入以下命令,在项目中安装 IronXL 库。
Install-Package IronXL.Excel
Install-Package IronXL.Excel
这将在我们的项目中安装 IronXL 和所需的依赖项。 您也可以直接从IronXL NuGet Package下载。
让我们编写代码,将员工列表转换为 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
我们以简单易行的方式从列表中创建了一个 Excel 文件。
IronXL 提供了全面的创建 XLSX 文件的教程、读取 Excel 文件的代码示例以及详细文档,帮助您以最佳方式利用其全面的 API。
总之,jQuery DataTables 已成为在 ASP.NET 网络应用程序中转换表格数据显示方式的强大工具。 其轻量级但功能丰富的特性有助于创建交互式表格,将排序、搜索和分页功能发挥到极致。 我们探讨了客户端处理的细微差别,利用浏览器的功能来处理较小的数据集,同时也承认在处理较大数据量时可能面临的挑战。 关于设置 ASP.NET Razor Page 应用程序和集成 jQuery DataTables 的分步指南为开发人员提供了实用的见解。 此外,IronXL.Excel 作为 Excel 相关任务的无缝解决方案的引入,为工具包增加了有价值的一层,实现了高效的数据导出。 有了这些工具,开发人员就能以引人入胜、易于理解的方式展示数据,从而提升用户体验。
IronXL 提供多种许可选项,具体取决于开发人员、项目和再分发需求的数量。 许可证是永久性的,包括免费支持和更新。