跳過到頁腳內容
.NET幫助

Jquery Datatable(開發者的工作原理)

資料呈現是網頁開發的重要一環,在處理表格資料時,擁有互動且功能豐富的表格是不可或缺的。 jQuery DataTables 是一個功能強大的 JavaScript 函式庫,提供先進的功能來建立動態與回應式表格。 在這篇文章中,我們將探討如何在 ASP.NET 網路應用程式中整合並使用 jQuery DataTables 來強化表格資料的呈現。

如何在 ASP.NET Web App 中使用 jQuery DataTables?

1.建立或開啟 Web 應用程式。 2.安裝 Entity Framework 套件。 3.新增模型、DB 上下文和控制器。 4.新增 DB 連接字串並設定組態。 5.新增遷移和更新資料庫。 6.新增 jQuery DataTables 的用戶端函式庫。 7.新增 HTML 表格和 JavaScript 程式碼。 8.建立並執行應用程式。 9.使用 IronXL.Excel Manipulation 將資料匯出至 Excel。

什麼是 jQuery DataTables?

jQuery DataTables 是一個輕量、靈活且功能豐富的 jQuery 外掛程式,用來處理表格資料。 它提供廣泛的功能,例如排序、搜尋和分頁,使其成為以人性化方式呈現大型資料集的理想選擇。

用戶端處理

在客戶端處理中,賦予瀏覽器在本機處理資料集的權力。 jQuery DataTables 透過其強大的功能,可直接在使用者的瀏覽器中進行動態互動與資料操作。 雖然這種方法在處理較小的資料集時可以無縫運作,但在處理大量資料集時可能會因為潛在的效能瓶頸和增加的資源消耗而面臨挑戰。

在這篇文章中,我們將探討 ASP.NET Razor Page 應用程式中的用戶端處理,強調它為較小資料集所提供的優勢,並深入剖析潛在的注意事項和最佳化,以確保順暢和反應迅速的使用者體驗。

在 ASP.NET Web 應用程式中開始使用 jQuery DataTables

本文將使用以 .NET Framework 4.8 為目標的 ASP.NET Razor Page Web 應用程式。您可以根據需求使用 Blazor、MVC 或 Web 表單。

本文將採用 Code-First 方法。 您可以依自己的喜好使用資料庫第一法。 我們需要安裝下列套件,以便使用 Code First Approach。

1.Microsoft.EntityFrameworkCore 2.Microsoft.EntityFrameworkCore.Design 3.Microsoft.EntityFrameworkCore.SqlServer 4.Microsoft.EntityFrameworkCore.Tools

使用 NuGet Package Manager Console 中的 Install-Package 指令安裝上述套件,或從 NuGet Package Manager 解決方案中搜尋安裝。

讓我們在 Program.cs 中加入 Model class、ApplicationDbContext Class、Controller、Connection String 和服務設定,以建立我們的專案。

新增模型類別

在這個範例中,我使用 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

新增員工控制器

新增 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;"
}

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)
$vbLabelText   $csharpLabel

運行遷移

下一步是執行遷移,因為我們使用的是 Code First Approach。 在套件管理員控制台執行下列指令。

Add-Migration init
Add-Migration init
SHELL

此指令將建立轉換。 現在,執行下列指令,將此轉換套用至資料庫。

update-database
update-database
SHELL

現在我們的專案已經設定完成,資料庫也準備好了,我們只需要加入 jQuery 函式庫和 HTML 表格,就可以完成我們的使用者介面了。 在本範例中,我們使用 SQL Server 作為資料來源,但您也可以使用任何其他資料庫。

新增 jQuery DataTables 函式庫

我們需要在專案中加入 jQuery DataTables 函式庫,它是 jQuery JavaScript 函式庫的表格增強外掛。 我們可以在專案上按一下滑鼠右鍵,選擇"新增",然後選擇"新增用戶端程式庫"。 將會出現一個小視窗,我們可以在此搜尋"jquery datatables"並進行安裝,如下圖所示:

 新增 jQuery DataTables Library

新增 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。 顯示的資料如下:

!a href="/static-assets/pdf/blog/jquery-datatable-guide/jquery-datatable-guide-2.webp">jQuery DataTables Output

現在,分頁在客戶端執行,因此完整的資料會從伺服器傳送,如下所示:

Pagination

輸出 UI

我們可以搜尋、排序及變更頁面,所有的動作都會在客戶端執行,如下圖所示:

!a href="/static-assets/pdf/blog/jquery-datatable-guide/jquery-datatable-guide-4.webp">Output UI

IronXL 簡介

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

在套件管理員控制台輸入以下指令,即可在專案中安裝 IronXL 函式庫。

Install-Package IronPdf

這將會在我們的專案中安裝 IronXL 和所需的相依性。 您也可以直接從 IronXL NuGet Package 下載。

將資料匯出至 Excel

讓我們編寫程式碼,將我們的 Employee List 轉換成 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 檔案。

OUTPUT Excel File

IronXL 提供全面的 建立 XLSX 檔案的教學讀取 Excel 檔案的程式碼範例,以及 詳細的說明文件,協助您以最佳的方式使用其全面的 API。

結論

總而言之,jQuery DataTables 已經成為 ASP.NET 網路應用程式中,轉換表格資料呈現的強大資產。 其輕量級但功能豐富的特性有助於建立互動式表格,將排序、搜尋和分頁功能發揮到極致。 我們探討了客戶端處理的細微差異,利用瀏覽器的功能來處理較小的資料集,同時也承認在處理較大資料量時可能面臨的挑戰。 有關設定 ASP.NET Razor Page 應用程式和整合 jQuery DataTables 的逐步指南,可為開發人員提供實用的深入見解。 此外,IronXL.Excel 作為 Excel 相關任務的無縫解決方案的介紹,也為工具包增加了寶貴的一層,可實現高效率的資料匯出。 有了這些工具,開發人員就能以引人注目且易於使用的方式呈現資料,進而提升使用者體驗。

IronXL 提供多種授權選項,視開發人員、專案和再散佈需求的數量而定。 授權是永久性的,並包含免費的支援與更新。

常見問題解答

jQuery DataTables 如何增強 ASP.NET 網路應用程式中的資料呈現?

jQuery DataTables 透過提供排序、搜尋和分頁等功能來增強資料的呈現,讓使用者可以更輕鬆地以回應式和友善的方式與大型資料集互動。

在 ASP.NET Razor Page 應用程式中整合 jQuery DataTables 的基本步驟是什麼?

若要在 ASP.NET Razor Page 應用程式中整合 jQuery DataTables,您必須先設定模型、DbContext 和控制器,設定資料庫連線,並使用 Entity Framework 的 Code-First 方法實作用戶端處理,以有效率地管理資料。

在管理大型資料集時,伺服器端處理對 jQuery DataTables 有何益處?

伺服器端處理 jQuery DataTables 的優點在於可將資料作業卸載至伺服器端,以提升處理大型資料集時的效能與效率,相較之下,用戶端處理大量資料時可能會變慢。

IronXL 在從 ASP.NET 應用程式匯出資料至 Excel 的過程中扮演什麼角色?

IronXL 可讓開發人員透過建立新工作簿、從資料集中填入資料行並儲存為 Excel 檔案,將資料匯出至 Excel。它簡化了 Excel 檔案的操作,而不需要 Microsoft Office。

如果沒有 Microsoft Office,是否可以在 .NET 應用程式中處理 Excel 檔案?

是的,IronXL for .NET 可讓 .NET 應用程式獨立於 Microsoft Office 來處理 Excel 檔案,支援各種格式,例如 XLS、XLSX、CSV 和 TSV。

在 .NET 專案中使用 IronXL 有哪些授權選項?

IronXL 根據開發人員、專案和發行需求的數量,提供各種授權選項。授權是永久性的,並包含免費支援與更新。

在 ASP.NET 中使用 jQuery DataTables 的 Code-First 方法有哪些優點?

ASP.NET 中的 Code-First 方法與 jQuery DataTables 支援資料庫模型與上下文的簡易設定與配置,允許動態資料管理,並與前端 DataTables 整合以增強互動性。

如何排除 ASP.NET 應用程式中 jQuery DataTables 的常見問題?

jQuery DataTables 的常見問題可透過以下方式解決:確保正確包含腳本與樣式表、驗證資料來源路徑、檢查控制台錯誤以確認 JavaScript 問題,以及確認伺服器端處理設定是否正確。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。