在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
ASP.NET 开发人员通常会寻求高效的方法来呈现具有排序、搜索和分页等高级功能的表格数据或 HTML 表格。 DataTables.NET 是一个强大的 jQuery 和 JavaScript 库,以及一个高度灵活的工具,可促进在网络应用程序中创建交互式和功能丰富的表格。 在本文中,我们将探讨如何将 DataTables.NET 分发文件(一种用于服务器端处理的表格增强库)集成到 ASP.NET 项目中,以增强表格数据的显示效果和用户体验。
创建 ASP.NET 网络应用程序
添加 DataTables 客户端样式包
安装 Entity Framework 核心软件包,仅安装核心软件
添加模型类、控制器和 Razor 页面
在 JS 文件中添加 JavaScript 代码
设置配置
构建并运行程序
DataTables.NET 是一个 jQuery JavaScript 库,允许您在 .NET 应用程序中创建和操作交互式表格。 它基于 jQuery DataTables 插件,可为动态和静态 HTML 表格提供分页、排序、过滤和滚动等全面的 API 功能。 这是一个表格增强库,可与各种数据源(如 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 应用程序中实现服务器端处理,演示如何有效地处理和显示大量数据集,同时提高网络应用程序的整体性能。
首先,我们需要将 DataTables.NET 客户端库添加到我们的项目中。 本文将使用基于.NET 8的ASP.NET Core Web应用程序(Razor Pages)项目。您可以根据需要使用任何Web应用程序项目。
要添加客户端库,请右键单击 "解决方案">"添加">"客户端库",然后搜索数据表,如下图所示。
现在,我们需要添加模型类、数据库上下文、控制器、HTML 表格和 AJAX 调用。
但在此之前,我们需要安装 EntityFramework NuGet 软件包,以便将我们的应用程序与数据库连接起来。 本文将使用 "代码优先 "方法,您也可以根据自己的偏好使用 "数据库优先 "方法。
安装以下本地托管软件包:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
使用 NuGet 软件包管理器控制台中的 install-package 命令安装上述软件包,或从 NuGet 软件包管理器解决方案中搜索安装。
我在本例中使用了产品模型类,您可以根据自己的要求使用。
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; }
}
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; }
}
我们将在 wwwroot>js 文件夹内添加 ProductDatatables.js,用于添加分页、搜索等高级控件。
//add advanced interaction controls
$(document).ready(function () {
$("#productDatatable").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
"url": "/api/Product",
"type": "POST",
"datatype": "json"
},
"columnDefs": [{
"targets": [0].data,
"visible": false,
"searchable": false
}],
"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 },
{
"render": function (data, row) { return "<a href="#" class='btn btn-danger' onclick=DeleteProduct('" + row.id + "'); >Delete</a>"; }
},
]
});
});
现在,我们需要添加一个 HTML 表格。
在 index.cshtml 文件中编写以下代码,添加一个静态 HTML 页面。
//static HTML page
@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>
}
//static HTML page
@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>
}
我们需要添加控制器。
添加产品控制器,用于创建端点和直接拉取请求。
[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.ToList();
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 ex)
{
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.ToList();
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 ex)
{
throw;
}
}
}
在这里,我们在服务器端实现了分页和搜索功能。
现在,我们需要设置数据库并在 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. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
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. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.MapRazorPages();
app.Run();
}
我们需要运行迁移,因为我们采用的是代码优先的方法。
在软件包管理器控制台中运行以下命令。
Add-Migration init
上述命令将创建一个迁移。 现在,我们需要将这些迁移应用到数据库中。 在软件包管理器控制台中运行以下命令。
Update-Database
上述命令将在我们的数据库中创建表格。 在产品表中添加虚拟数据,您可以从Mockaroo生成随机数据。
现在,请构建并运行此应用程序。
我们可以看到,我们有一个交互性很强的用户界面,带有高级交互控件。
现在,在服务器端实现了分页,如下所示。
然后,数据将通过丰富的用户界面控件呈现在客户端上。
您可以通过点击探索DataTables.NET文档来了解更多内容。
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 库。
Install-Package ironXL.Excel
这将在我们的项目中安装 IronXL 和所需的依赖项。
让我们编写一段代码,将产品列表转换为 Excel 文件。
public void ExportToExcel(List<Product> productList)
{
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet ws = wb.DefaultWorkSheet;
int rowCount = 1;
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");
}
public void ExportToExcel(List<Product> productList)
{
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet ws = wb.DefaultWorkSheet;
int rowCount = 1;
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");
}
我们以非常简单轻松的方式将列表创建为 Excel 文件。
IronXL提供全面的创建XLSX文件教程、读取Excel的代码示例,以及API文档,以最佳方式使用其全面的API。
在优化 ASP.NET 性能方面,我们完全依赖于 Only Core Software,确保开发环境精简高效。 利用 DataTables.NET 作为本地托管软件包可进一步提高响应速度,最大限度地减少外部依赖性,从而简化数据处理和 Excel 导出。 此外,在这个优化的、自成一体的生态系统中,代码贡献将变得高效无缝。
IronPDF 是一种解决方案,旨在将网页、URL 和 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");
}
}
总之,在 ASP.NET 分发 repo 项目中利用 DataTables.NET 进行服务器端处理被证明是有效处理大量数据集的良好策略。 这种方法通过以可管理的块状传输数据、减少带宽使用和增强用户体验来确保优化性能。 IronXL.Excel 的集成进一步扩展了应用程序的功能,可以毫不费力地将表格数据导出到 Excel,以便进行全面的数据分析和报告。
通过采用这些技术,开发人员可以创建在丰富的交互性和资源效率之间取得平衡的网络应用程序,为用户提供无缝的响应式体验,尤其是在涉及大型数据集的情况下。 IronXL提供各种IronXL授权选项,具体取决于开发人员的数量、项目和再分发需求。 许可证是永久性的,包括免费支持和更新。