.NET 幫助

Jquery Datatable(如何為開發者運作)

發佈 2024年1月27日
分享:

數據呈現是網頁開發的一個關鍵方面,而在處理表格數據時,擁有一個互動性強且功能豐富的表格是必不可少的。 jQuery DataTables 是一個強大的 JavaScript 庫,提供了創建動態和響應式表格的先進功能。在本文中,我們將探討如何整合和使用 jQuery DataTables 在一個 ASP.NET 網頁應用程式以提升表格數據的呈現。

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

  1. 建立或打開一個網頁應用程式。

  2. 安裝實體框架包。

  3. 添加模型、DB 上下文和控制器。

  4. 添加 DB 連接字串並設置配置。

  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 Page 網頁應用程式。您可以根據需求使用 Blazor、MVC 或 Web Forms。

本文將使用代碼優先的方法。您可以根據偏好使用資料庫優先的方法。為了使用代碼優先的方法,我們需要安裝以下套件:

  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 類別來設置 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
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;"
}

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)
VB   C#

執行遷移

接下來的步驟是執行遷移,因為我們使用的是 Code First 方法。在套件管理員主控台中執行以下命令。

Add-Migration init

此命令將創建遷移。現在,運行以下命令將此遷移應用到數據庫。

update-database

現在我們的專案已設置完成且資料庫也已準備就緒,只需添加jQuery函式庫和HTML表格來使我們的UI準備好。在此範例中,我們使用了SQL Server作為數據來源,但您可以使用其他任何資料庫。

添加 jQuery DataTables 庫

我們需要在項目中添加 jQuery DataTables 庫,這是一個用於增強 jQuery JavaScript 庫的表格插件。我們可以通過右鍵點擊項目,選擇「Add」,然後選擇「Add Client-Side Library」來添加它。此時會出現一個小窗口,在那裡我們可以搜索「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>
}

我們需要將 EmployeeDatatable.js 文件添加到 wwwroot/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 }
        ]
    });
});
JAVASCRIPT

我們已經使用了功能豐富的 jQuery DataTables 庫。這個強大的 jQuery 插件使我們能夠在客戶端輕鬆實現高級功能。

現在,構建並運行這個應用程序。

輸出

我們可以看到,在 jQuery 的幫助下,我們在 ASP.NET 中準備了一個非常互動的用戶界面。顯示的數據如下:

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 提供全面的 教程, 程式碼範例,和 文檔 幫助您以最佳方式利用其全面的API。

結論

總結來說,jQuery DataTables 已成為轉換 ASP.NET 網頁應用程式中表格資料呈現的強大工具。它輕量卻功能豐富,促成交互式表格的創建,使排序、搜索和分頁功能顯著提升。我們探討了用戶端處理的細微之處,利用瀏覽器的能力處理較小的數據集,同時也注意到處理較大數據量可能面臨的挑戰。設置 ASP.NET Razor Page 應用程式並整合 jQuery DataTables 的逐步指南為開發者提供了實用的見解。此外,引入 IronXL 作為無縫解決 Excel 相關任務的工具,為開發工具包增加了一個有價值的層面,實現高效的數據導出。擁有這些工具,開發者可以通過以引人注目的方式呈現數據,提升用戶體驗。

IronXL 提供多種授權選項,依據開發者數量、專案數量和重新分發需求來選擇。授權是永久性的,並包括免費的支援和更新。

< 上一頁
C# 陣列排序(開發者是如何工作的)
下一個 >
C# 計時器(它如何對開發者運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >