跳至頁尾內容
.NET幫助

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

資料呈現是網頁開發中的重要方面,當處理表格資料時,擁有一個互動性強且功能豐富的表格是必不可少的。 jQuery DataTables 是一個強大的 JavaScript 程式庫,提供建立動態和響應式表格的高級功能。 在本文中,我們將探討如何在 ASP.NET 網頁應用程式中整合和使用 jQuery DataTables 來提升表格資料的呈現。

如何在 ASP.NET 網頁應用程式中使用 jQuery DataTables?

  1. 建立或打開一個網頁應用程式。
  2. 安裝 Entity Framework 套件。
  3. 新增模型、資料庫上下文和控制器。
  4. 新增資料庫連接字串並設置配置。
  5. 新增遷移並更新資料庫。
  6. 新增 jQuery DataTables 的客戶端程式庫。
  7. 新增 HTML 表格和 JavaScript 程式碼。
  8. 構建並運行應用程式。
  9. 使用 IronXL for Excel Manipulation 將資料導出到 Excel。

什麼是 jQuery DataTables?

jQuery DataTables 是一個輕量且靈活的 jQuery 插件,用於處理表格資料。 它提供了多種功能,如排序、搜尋和分頁,使其成為以直觀方式展示大型資料集的理想選擇。

客戶端處理

在客戶端處理中,瀏覽器能夠本地處理資料集。 jQuery DataTables 通過其強大的功能,允許在使用者瀏覽器中直接互動並操控資料。 雖然此方法對於較小的資料集運行順暢,但在處理龐大資料集時,由於潛在的性能瓶頸和增加的資源消耗,可能會面臨挑戰。

在本文中,我們將在 ASP.NET Razor Page 應用程式中探討客戶端處理,強調其對小型資料集的優勢,並提供確保平滑和響應性使用者體驗的潛在考慮和優化的見解。

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

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

本文中將使用 Code-First 方法。 您可以根據偏好使用 Database First 方法。 為使用 Code First 方法,我們需要安裝以下套件。

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.Design
  3. Microsoft.EntityFrameworkCore.SqlServer
  4. Microsoft.EntityFrameworkCore.Tools using NuGet Package Manager Console 或使用 NuGet 套件管理器解決方案中的 Install-Package 命令來安裝上述套件,或搜尋並安裝它們。

讓我們通過在 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

運行遷移

下一步是運行遷移,因為我們使用的是 Code First 方法。 在Package Manager Console中運行以下命令。

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 程式庫

新增 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 插件使我們能夠在客戶端側以最小的努力實現高級功能。

現在,建置並運行此應用程式。

輸出

我們可以看到,有了 jQuery 在 ASP.NET 中的幫助,我們已經準備好了非常互動的使用者介面。 顯示的資料如下:

jQuery DataTables 輸出

現在,分頁在客戶端側實現,因此完整資料從伺服器發送,如下所示:

分頁

輸出UI

我們可以搜尋、排序和更改頁面,所有這些都將在客戶端側執行,如下所示:

輸出使用者介面

介紹 IronXL

IronXL for .NET Excel 文件操作 是一個允許您在 .NET 應用程式中處理 Excel 文件的程式庫。 它可以建立、讀取、編輯和儲存 Excel 文件於多種格式,如 XLS、XLSX、CSV 和 TSV。它不需要安裝 Microsoft Office 或 Excel 互操作。 它支持 .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 文件。

輸出 Excel 文件

IronXL 提供全面的如何建立 XLSX 文件的教程閱讀 Excel 文件的程式碼範例詳細文件,幫助您以最佳方式利用其全面的 API。

結論

總之,jQuery DataTables 已成為在 ASP.NET 網頁應用程式中改變表格資料呈現的強大工具。 其輕量但功能豐富的特性便於建立互動式表格,使排序、搜尋和分頁成為重點。 我們探討了客戶端處理的細微差別,利用瀏覽器的能力處理較小的資料集,同時承認對於大型資料量的潛在挑戰。 關於設置 ASP.NET Razor Page 應用程式和整合 jQuery DataTables 的逐步指南為開發者提供了實用的見解。 此外,IronXL 作為一種無縫處理 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。

是否可以在.NET應用中處理Excel文件而無需Microsoft Office?

可以,IronXL使.NET應用無需Microsoft Office即可獨立處理Excel文件,支援多種格式如XLS、XLSX、CSV和TSV。

IronXL在.NET專案中的授權選擇是什麼?

IronXL提供基於開發者人數、專案和分發需求的多種授權選擇。授權是永久的,包含免費支援和更新。

在ASP.NET中使用jQuery DataTables的Code-First方法有什麼好處?

ASP.NET中使用jQuery DataTables的Code-First方法支持簡單的資料庫模型和上下文設定和配置,可動態資料管理並與前端DataTables進行整合以增強互動性。

如何在ASP.NET應用中解決jQuery DataTables常見問題?

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

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話