跳過到頁腳內容
.NET幫助

Datatables .NET(開發者的工作原理)

ASP.NET開發人員經常尋求以高効率展示表格資料或HTML表格的方法,這些表格提供如排序、搜尋和分頁等進階功能。 DataTables.NET 是一個強大的jQuery、JavaScript程式庫,這是一個高度靈活的工具,可在網頁應用程式中輕鬆建立具有豐富功能的互動式表格。 在本文中,我們將探討如何在ASP.NET專案中整合DataTables.NET發行檔案,這是一個增強表格的程式庫,支持伺服器端處理,以提升表格資料的展示和使用者體驗。

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

  1. 建立ASP.NET網頁應用程式
  2. 添加DataTables客戶端樣式包
  3. 安裝Entity Framework Core軟體包,只需安裝核心軟體
  4. 添加模型類別、控制器和Razor頁面
  5. 在JS檔案中添加JavaScript代碼
  6. 設置配置
  7. 構建並運行程式
  8. 使用IronXL for Excel Data Export將資料導出到Excel檔案中

什麼是DataTables.NET?

DataTables.NET是允許您在.NET應用程式中建立和操作互動式表格的jQuery JavaScript程式庫。 它基於jQuery DataTables插件,提供分頁、排序、過濾和滾動等全面的API功能,適用於動態和靜態HTML表格。 這是一個增強表格的程式庫,可以與各種資料來源一起使用,例如SQL資料庫、AJAX或內存中的物件。

伺服器端處理

考慮一個情景,您有一個API端點提供大量產品資料集。 標準方法涉及jQuery DataTables對此API進行AJAX調用,獲取以JSON格式的產品列表,並渲染HTML表格。 這被稱為客戶端處理,對較小資料集(通常為100到1000條記錄)是有效的。 但是,當資料集擴展到10,000條記錄或更多時會發生什麼?

當處理大量記錄時,一次將整個資料集發送到瀏覽器變得不切實際。 一次傳輸10,000條記錄不僅浪費帶寬,還會占用瀏覽器資源。 在這種情況下,伺服器端處理是一種關鍵的替代方法,可以優化性能。

在伺服器端處理中,API將資料以可管理的塊進行傳輸,通常每頁分頁約50條記錄。 通過這樣做,載入時間顯著改善,因為jQuery DataTables現在僅載入適量的記錄(大約50條),而不是一次處理整個資料集。 此方法減少CPU和帶寬的使用量,創造了API與DataTable之間更有效的交互。

在本文中,我們將探討在ASP.NET Razor Page應用程式中伺服器端處理的實施,展示如何有效處理和顯示龐大資料集,同時提升網頁應用程式的整體性能。

如何在ASP.NET 8中開始使用DataTables.NET?

要開始使用,我們需要將DataTables.NET客戶端程式庫添加到我們的專案中。 本文將使用ASP.NET Core Web App(Razor Pages)專案搭配.NET 8。您可根據需求選擇任何Web App專案。

要添加客戶端程式庫,右鍵單擊解決方案>添加>客戶端程式庫,然後搜索資料表,如下所示。

DataTables.NET(開發者如何使用): 圖1 - 添加客戶端程式庫

現在,我們需要添加模型類別、數據庫上下文、控制器、HTML表格和AJAX調用。

但在那之前,我們需要安裝EntityFramework NuGet套件以將應用程式連接至數據庫。 本文將使用Code First方法,您可以根據偏好使用Database First。

安裝以下本地托管的套件:

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

使用NuGet Package Manager Console中的install-package命令安裝上述套件,或者從NuGet Package Manager解決方案中搜索安裝它。

添加模型類別

在這個例子中,我使用Product模型類別,您可以根據自己的需要使用它。

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
$vbLabelText   $csharpLabel

添加ApplicationDBContext類別

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
$vbLabelText   $csharpLabel

添加高級互動控制

我們將在ProductDatatables.js以添加高級控件,如分頁、搜索等。

// Initialize the DataTables plugin for the HTML element with 'productDatatable' ID
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true, // Enable processing indicator
        "serverSide": true, // Enable server-side processing
        "ajax": {
            "url": "/api/Product", // API endpoint for fetching product data
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            // Define properties for columns
            "targets": [0],
            "visible": false, // Hide the 'Id' column
            "searchable": false // Disable searching for the 'Id' column
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                // Add a 'Delete' button with an onclick event for deleting the product
                "render": function (data, type, row) { 
                    return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "');>Delete</a>"; 
                }
            }
        ]
    });
});
// Initialize the DataTables plugin for the HTML element with 'productDatatable' ID
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true, // Enable processing indicator
        "serverSide": true, // Enable server-side processing
        "ajax": {
            "url": "/api/Product", // API endpoint for fetching product data
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            // Define properties for columns
            "targets": [0],
            "visible": false, // Hide the 'Id' column
            "searchable": false // Disable searching for the 'Id' column
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                // Add a 'Delete' button with an onclick event for deleting the product
                "render": function (data, type, row) { 
                    return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "');>Delete</a>"; 
                }
            }
        ]
    });
});
JAVASCRIPT

現在,我們需要添加HTML表格。

添加HTML表格

index.cshtml檔案中撰寫以下代碼以添加靜態HTML頁面。

@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="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product Name</th>
                    <th>Product Price</th>
                    <th>Product Weight</th>
                    <th>Product Description</th>
                    <th>Product Manufacturing Date</th>
                    <th>Product Expiry Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </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/ProductDatatable.js"></script>
}

我們需要添加控制器。

添加Product控制器

添加Product控制器以創建端點並直接拉取請求。

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }

    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form["draw"].FirstOrDefault();
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToLis();

            // Filtering data based on provided search value
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)
                                            || m.ProductDescription.Contains(searchValue)
                                            || m.Id.ToString().Contains(searchValue)).ToList();
            }

            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception)
        {
            throw;
        }
    }
}
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }

    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form["draw"].FirstOrDefault();
            var start = Request.Form["start"].FirstOrDefault();
            var length = Request.Form["length"].FirstOrDefault();
            var searchValue = Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToLis();

            // Filtering data based on provided search value
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)
                                            || m.ProductDescription.Contains(searchValue)
                                            || m.Id.ToString().Contains(searchValue)).ToList();
            }

            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception)
        {
            throw;
        }
    }
}
$vbLabelText   $csharpLabel

在這裡,我們已在伺服器端實施分頁和搜索。

現在,我們需要設置我們的數據庫並將配置添加到Program.cs類別中。 如果您使用的是.NET 5或更低版本,則可能需要在Startup.cs類別中進行此操作。

首先,在appsettings.json檔案中添加以下連接字串。

"ConnectionStrings": {
   "ProductDB": "Server=localserver\\SQLEXPRESS;Database=ProductDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
}

現在將以下代碼添加到Program.cs類別中。

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<ApplicationDBContext>(options =>
    {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
    });
    builder.Services.AddControllers();
    // Add services to the container.
    builder.Services.AddRazorPages();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days.
         app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();
    app.MapRazorPages();
    app.Run();
}
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<ApplicationDBContext>(options =>
    {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
    });
    builder.Services.AddControllers();
    // Add services to the container.
    builder.Services.AddRazorPages();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days.
         app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();
    app.MapRazorPages();
    app.Run();
}
$vbLabelText   $csharpLabel

我們需要運行遷移,因為我們使用的是代碼優先方法。

在包管理器控制台中運行以下命令。

Add-Migration init
Add-Migration init
SHELL

上述命令將創建一個遷移。 現在我們需要將這些遷移應用到我們的數據庫中。 在包管理器控制台中運行以下命令。

Update-Database
Update-Database
SHELL

上述命令將在我們的數據庫中創表。 在Product表中添加虛擬資料。 您可以從Mockaroo生成隨機數據。

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

輸出

我們可以看到,我們擁有一個非常互動的UI,帶有高級互動控制。

DataTables.NET(開發者如何使用): 圖2 - 輸出

現在,分頁是在伺服器端實施的,如下所示。

DataTables.NET(開發者如何使用): 圖3 - 分頁

輸出UI

然後,資料在客戶端以豐富的UI控件呈現。

DataTables.NET(開發者如何使用): 圖4 - UI

您可以點擊探索DataTables.NET文檔來獲得更多資訊。

IronXL介紹

IronXL - Excel Library for .NET 是一個允許您在.NET應用程式中使用Excel檔案的程式庫。 它可以創建Excel試算表讀取CSV檔案編輯Excel文件,以及以多種格式導出到Excel,例如XLS、XLSX、CSV和TSV。不需要安裝Microsoft Office或Excel Interop。 它支持.NET 8、7、6、5、Core、Framework和Azure。

我們經常需要將資料導出到Excel或CSV檔案中。 IronXL是最佳選擇。 現在,我們將撰寫代碼將我們的資料導出到Excel檔案中。

安裝IronXL

通過在包管理器控制台中輸入以下命令,安裝IronXL程式庫到我們的專案中。

Install-Package IronPdf

這將在我們的專案中安裝IronXL和所需的依賴項。

將資料導出到Excel

讓我們編寫代碼將我們的產品列表轉換成Excel檔案。

public void ExportToExcel(List<Product> productList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Create a new workbook instance
    WorkSheet ws = wb.DefaultWorkSheet; // Access the default worksheet
    int rowCount = 1;

    // Iterate over the product list and fill the worksheet
    foreach (Product product in productList)
    {
        ws["A" + rowCount].Value = product.Id.ToString();
        ws["B" + rowCount].Value = product.ProductName;
        ws["C" + rowCount].Value = product.ProductDescription;
        ws["D" + rowCount].Value = product.ProductPrice;
        ws["E" + rowCount].Value = product.ProductWeight;
        ws["F" + rowCount].Value = product.ProductManufacturingDate;
        ws["G" + rowCount].Value = product.ProductExpiryDate;
        rowCount++;
    }
    wb.SaveAs("product.xlsx"); // Save the workbook as an Excel file
}
public void ExportToExcel(List<Product> productList)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX); // Create a new workbook instance
    WorkSheet ws = wb.DefaultWorkSheet; // Access the default worksheet
    int rowCount = 1;

    // Iterate over the product list and fill the worksheet
    foreach (Product product in productList)
    {
        ws["A" + rowCount].Value = product.Id.ToString();
        ws["B" + rowCount].Value = product.ProductName;
        ws["C" + rowCount].Value = product.ProductDescription;
        ws["D" + rowCount].Value = product.ProductPrice;
        ws["E" + rowCount].Value = product.ProductWeight;
        ws["F" + rowCount].Value = product.ProductManufacturingDate;
        ws["G" + rowCount].Value = product.ProductExpiryDate;
        rowCount++;
    }
    wb.SaveAs("product.xlsx"); // Save the workbook as an Excel file
}
$vbLabelText   $csharpLabel

我們已經用非常簡單的方式從列表中創建了一個Excel檔案。

DataTables.NET(開發者如何使用): 圖5 - Excel輸出

IronXL提供了全面的關於創建XLSX文件的教程,以及讀取Excel的代碼範例,和API文檔,以最佳方式使用其綜合API。

在優化ASP.NET性能時,我們僅依靠核心軟體,確保一個精簡且有效的開發環境。 利用DataTables.NET作為本地托管套件,進一步提升了響應性,最大限度地減少外部依賴性,以實現精簡的數據處理和Excel導出。 此外,在這個優化且自含的生態系統中,高效編寫代碼變得更加無縫。

IronPDF是一種方案,專為將網頁、網址和HTML轉換為PDF文件而設計。 生成的PDF保留源網頁的原始格式和風格元素。 這種工具在為諸如報告和發票的基於網頁的內容進行PDF展示方面特別有效。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

結論

總之,在ASP.NET發行倉庫專案中,利用DataTables.NET進行伺服器端處理證明是一種有效處理大量資料集的良好策略。 此方法通過將資料以可管理的塊進行傳輸來確保性能最佳化,減少帶寬使用,增強用戶體驗。 IronXL的整合進一步擴展了應用程式的能力,使得輕鬆將表格資料導出到Excel,以便全面的資料分析和報告。

通過採用這些技術,開發人員能夠創建平衡了豐富互動性和資源效率的網頁應用程式,特別是在涉及大規模數據集的情況下,為用戶提供無縫和響應迅速的體驗。 IronXL提供了多種IronXL的授權選項,根據開發人員的數量、專案和再分發需求而定。 這些授權是永久性的,並包括免費支援和更新。

常見問題解答

如何將 DataTables.NET 整合到 ASP.NET 專案中?

要將 DataTables.NET 整合到 ASP.NET 專案中,您需要創建一個 ASP.NET Web 應用程式,添加 DataTables 客戶端樣式套件,安裝 Entity Framework Core 套件,添加模型類別、控制器和 Razor Pages,配置 JavaScript 以進行伺服器端處理,然後構建並運行您的專案。

DataTables.NET 中的伺服器端處理是什麼?

DataTables.NET 中的伺服器端處理涉及從伺服器向客戶端傳輸可管理的數據塊,而不是一次加載整個數據集。這通過減少負載時間和最小化 CPU 和帶寬使用來提高性能,特別是在大型數據集的情況下。

為什麼伺服器端處理在 DataTables.NET 中很重要?

處理大型數據集時,伺服器端處理對優化性能至關重要。它允許伺服器僅將必要的數據發送到客戶端,進而減少瀏覽器的負擔並提高整體效率。

如何在 ASP.NET 應用程式中將表格數據導出到 Excel?

您可以使用 IronXL 庫將表格數據導出到 ASP.NET 應用程式中的 Excel。 IronXL 使您能夠直接從數據列表創建和操作 Excel 文件,而不需要 Microsoft Office 或 Excel Interop。

如何在 ASP.NET 中設置客戶端庫以使用 DataTables?

要在 ASP.NET 中設置客戶端庫,請在 Visual Studio 中右鍵點擊您的解決方案,選擇“添加”,然後選擇“客戶端庫”。您可以搜尋並添加所需的庫,例如 DataTables,以增強您的專案功能。

配置 DataTables.NET 以執行伺服器端處理的步驟有哪些?

要配置 DataTables.NET 的伺服器端處理,確保已設置模型類、數據庫上下文、控制器和 HTML 表格。您還需要進行 AJAX 調用並在 JavaScript 文件中配置伺服器端處理邏輯,以處理數據提取和操作。

DataTables.NET 的篩選和分頁是如何工作的?

DataTables.NET 中的篩選和分頁是通過伺服器端處理來管理的。伺服器根據搜尋條件篩選數據,並通過將數據塊發送到客戶端來管理分頁,從而確保高效的數據處理。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me