您好,登錄后才能下訂單哦!
在C#中處理大型數(shù)據(jù)表的分頁和搜索,通常需要使用ASP.NET Web API或MVC來創(chuàng)建一個(gè)Web服務(wù)。這個(gè)Web服務(wù)可以接收AJAX請求,并返回分頁和搜索后的數(shù)據(jù)。以下是一個(gè)簡單的示例,展示了如何在C#中使用ASP.NET MVC和Entity Framework實(shí)現(xiàn)分頁和搜索功能。
Product
的模型:public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
ProductRepository
的倉庫類,用于處理數(shù)據(jù)庫操作。在這個(gè)類中,我們將實(shí)現(xiàn)分頁和搜索功能:public class ProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<Product>> GetProductsAsync(int page, int pageSize, string searchTerm)
{
var query = _context.Products.AsQueryable();
if (!string.IsNullOrEmpty(searchTerm))
{
query = query.Where(p => p.Name.Contains(searchTerm));
}
return await query
.OrderBy(p => p.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
}
}
ProductsController
的控制器,用于處理AJAX請求:public class ProductsController : Controller
{
private readonly ProductRepository _repository;
public ProductsController(ProductRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task<IActionResult> GetProducts(int page, int pageSize, string searchTerm)
{
var products = await _repository.GetProductsAsync(page, pageSize, searchTerm);
return Json(products);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="searchTerm" placeholder="Search..." />
<button id="searchButton">Search</button>
<table id="productsTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$(document).ready(function () {
const pageSize = 10;
let currentPage = 1;
let searchTerm = "";
function loadProducts() {
$.get("/Products/GetProducts", { page: currentPage, pageSize: pageSize, searchTerm: searchTerm }, function (data) {
$("#productsTable tbody").empty();
data.forEach(function (product) {
$("#productsTable tbody").append(`
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
</tr>
`);
});
});
}
$("#searchButton").click(function () {
searchTerm = $("#searchTerm").val();
currentPage = 1;
loadProducts();
});
// 初始化加載第一頁數(shù)據(jù)
loadProducts();
});
</script>
</body>
</html>
這個(gè)示例展示了如何在C#中使用ASP.NET MVC和Entity Framework實(shí)現(xiàn)大型數(shù)據(jù)表的分頁和搜索功能。當(dāng)然,你還可以根據(jù)需要對此進(jìn)行擴(kuò)展和優(yōu)化。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。