.NET幫助 Jquery Datatable(開發者的工作原理) Curtis Chau 更新日期:9月 1, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 數據展示是網頁開發中的一個關鍵方面,當處理表格數據時,擁有一個具互動性和功能豐富的表格是必不可少的。 jQuery DataTables 是一個強大的 JavaScript 庫,它提供了創建動態和響應表格的高級功能。 在本文中,我們將探討如何在 ASP.NET 網頁應用中集成和使用 jQuery DataTables 以增強表格數據的展示。 如何在 ASP.NET 網頁應用中使用 jQuery DataTables? 創建或打開一個網頁應用。 安裝 Entity Framework 包。 添加模型、DB 上下文和控制器。 添加資料庫連接字串並設置配置。 添加遷移並更新資料庫。 添加 jQuery DataTables 的客戶端庫。 添加 HTML 表格和 JavaScript 代碼。 構建並運行應用。 使用 IronXL 進行 Excel 操作導出數據到 Excel。 什麼是 jQuery DataTables? jQuery DataTables 是一個輕量級、靈活、且功能豐富的 jQuery 插件,用於處理表格數據。 它提供了廣泛的功能,如排序、搜索和分頁,使其成為展示大型數據集時的一個理想選擇,且使用者界面友好。 客戶端處理 在客戶端處理中,瀏覽器能夠在本地處理數據集。 jQuery DataTables 通過其強大的功能,允許直接在用戶的瀏覽器中動態交互和操作數據。 雖然這種方法對於較小數據集運行很順暢,但在處理大型數據集時可能會面臨性能瓶頸和資源消耗增加的挑戰。 在本文中,我們將探討在 ASP.NET Razor Page 應用中進行客戶端處理,強調其對較小數據集提供的優勢,並提供可能的考量和最佳化的見解,以確保平順和響應的用戶體驗。 在 ASP.NET 網頁應用中開始使用 jQuery DataTables 本文將使用一個 ASP.NET Razor Page Web 應用,目標鎖定 .NET Framework 4.8。您可以根據需求使用 Blazor、MVC 或 Web Forms。 本文將使用代碼優先方法。 您可以根據偏好使用資料庫優先方法。 我們需要安裝以下包以使用代碼優先方法。 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools 使用 Install-Package 命令從 NuGet Package Manager Console 安裝上述包,或通過在 NuGet Package Manager 中搜索這些包進行安裝。 讓我們通過在 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 $vbLabelText $csharpLabel 添加 ApplicationDbContext 類 我們需要添加 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 $vbLabelText $csharpLabel 添加 Employee 控制器 添加 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) { // Log exception here 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) { // Log exception here 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 ' Log exception here Throw End Try End Function End Class $vbLabelText $csharpLabel 在這裡,我們使用 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) $vbLabelText $csharpLabel 運行遷移 下一步是運行遷移,因為我們正在使用代碼優先方法。 在稀包管理器控制台中運行以下命令。 Add-Migration init Add-Migration init SHELL 此命令將創建一個遷移。 現在,運行以下命令以將此遷移應用到資料庫中。 update-database update-database SHELL 現在,我們的專案已設置完成並且資料庫已準備好,我們只需添加 jQuery 庫和 HTML 表格來使用戶界面準備就緒。 在此示例中,我們使用了 SQL Server 作為數據源,但您可以使用任何其他資料庫。 添加 jQuery DataTables 庫 我們需要添加 jQuery DataTables 庫,這是一個用於 jQuery JavaScript 庫的表格增強插件,在我們的專案中。 我們可以通過右鍵點擊專案,選擇“添加”,然後選擇“添加客戶端庫”來添加它。 將出現一個小窗口,我們可以搜索“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 的高級功能,如過濾、分頁、搜索、排序等。 創建 EmployeeDatatable.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 } ] }); }); $(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,我們準備了一個非常交互的用戶界面。 顯示的數據如下: 現在,分頁實現在客戶端,因此完整數據從服務器發送,如下所示: 輸出 UI 我們可以搜索、排序和更換頁面,所有操作都將在客戶端進行,如下所示: IronXL 簡介 IronXL 用於 .NET Excel 文件操作 是一個允許您在 .NET 應用中處理 Excel 文件的庫。 它可以創建、讀取、編輯和保存多種格式的 Excel 文檔,如 XLS、XLSX、CSV 和 TSV。它不需要安裝 Microsoft Office 或 Excel Interop。 它支持 .NET 5、Core、Framework 和 Azure。 我們通常需要將數據導出到 Excel 或 CSV 文件中。 在這種情況下,IronXL 是最佳選擇。 現在,我們將編寫代碼將數據導出為 Excel 文件。 安裝 IronXL 通過在包管理器控制台輸入以下命令來安裝 IronXL 庫到您的專案。 Install-Package IronPdf 這將在我們的專案中安裝 IronXL 及其所需的依賴項。 您也可以直接從 IronXL NuGet 包下載它。 將數據導出至 Excel 讓我們編寫代碼將僱員列表轉換為 Excel 文件。 public void ExportToExcel(List<Employee> employeeList) { // Create a new workbook instance WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Get the default worksheet 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 Rows 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++; } // Save the workbook as an Excel file wb.SaveAs("Employee.xlsx"); } public void ExportToExcel(List<Employee> employeeList) { // Create a new workbook instance WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Get the default worksheet 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 Rows 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++; } // Save the workbook as an Excel file wb.SaveAs("Employee.xlsx"); } Public Sub ExportToExcel(ByVal employeeList As List(Of Employee)) ' Create a new workbook instance Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX) ' Get the default worksheet 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 Rows 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 ' Save the workbook as an Excel file wb.SaveAs("Employee.xlsx") End Sub $vbLabelText $csharpLabel 我們以一種簡單易行的方式從列表創建了一個 Excel 文件。 IronXL provides comprehensive tutorials on creating XLSX files, code examples for reading Excel files, and detailed documentation to help you utilize its comprehensive API in the best way possible. 結論 總之,jQuery DataTables 已經成為一個強大的資產,用於改變 ASP.NET 網頁應用中表格數據的展示。 其輕量但功能豐富的性質促進了交互性表格的創建,將排序、搜索和分頁推向前沿。 我們探索了客戶端處理的細微差別,利用瀏覽器的能力來處理較小的數據集,同時也承認較大數據量可能面臨的挑戰。 關於設置 ASP.NET Razor Page 應用和集成 jQuery DataTables 的分步指南為開發人員提供了實用的見解。 此外,引入 IronXL 作為一個無縫的 Excel 相關任務解決方案,為工具包增添了一層價值,實現高效的數據導出。 憑藉這些工具,開發人員可以通過以引人注目且易於訪問的方式展示數據來提升用戶體驗。 IronXL 提供多種授權選項,取決於開發人員數量、項目和重新分發需要。 許可是永久的,並包含免費的支持和更新。 常見問題解答 jQuery DataTables 如何在 ASP.NET 網絡應用程序中提升數據展示? jQuery DataTables 通過提供排序、搜尋和分頁等功能,增強數據展示,使用戶更容易在響應式和用戶友好的方式中互動大量數據集。 將 jQuery DataTables 集成到 ASP.NET Razor Page 應用程序的基本步驟是什麼? 要在 ASP.NET Razor Page 應用程序中集成 jQuery DataTables,首先設置模型、DbContext 和控制器,配置數據庫連接,並運用代碼優先(Code-First)方法和 Entity Framework 實施客戶端數據處理來高效管理數據。 在管理大量數據集時,服務端處理如何有利於 jQuery DataTables? 服務端處理通過將數據操作委託給服務器來提升性能和效率,特別是在處理大量數據集時,相比之下客戶端處理可能在處理大量數據時變得緩慢。 IronXL 在從 ASP.NET 應用程序導出數據到 Excel 中扮演什麼角色? IronXL 允許開發者通過創建新的工作簿,從數據集填充數據行,並保存為 Excel 文件來導出數據到 Excel。它簡化了 Excel 文件的操作,而無需使用 Microsoft Office。 是否可以在 .NET 應用程序中處理 Excel 文件而不使用 Microsoft Office? 是的,IronXL 使 .NET 應用程序可以獨立於 Microsoft Office 工作於 Excel 文件,支持多種格式如 XLS、XLSX、CSV 和 TSV。 用於 .NET 項目中的 IronXL 的許可選項有哪些? IronXL 根據開發人員數量、項目和分發要求提供各種許可選項。許可是永久的,包括免費支持和更新。 在 ASP.NET 中使用 jQuery DataTables 的代碼優先(Code-First)方法的優勢是什麼? 在 ASP.NET 中使用 jQuery DataTables 的代碼優先方法支持易於設置和配置數據庫模型和上下文,允許動態數據管理和前端 DataTables 的集成以增強交互性。 如何在 ASP.NET 應用程序中排除 jQuery DataTables 的常見問題? 可通過確認包含正確的腳本和樣式表、驗證數據源路徑、檢查控制台錯誤以解決 JavaScript 問題,並確認正確的服務器端處理設置來排除 jQuery DataTables 的常見問題。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 陣列排序(開發者的工作原理)C# Stopwatch(開發者的工作...