环境:
win10, .NET 6.0
问题描述
假设我数据库中有N个表,当我打开某页面时,每个表都先加载一部分(比如20条),点击表下某个按钮,再加载下一部分,如此循环直至加载完毕。
解决方案
基础版
数据库查询部分(Entity Framework)
BasicPartsDbContext.cs
1 2 3 4 5 6 7 8 9 | using System.Data.Entity; namespace WebApplication1.Models { public class BasicPartsDbContext:DbContext { public BasicPartsDbContext() : base ( "name=conn1" ) { } public DbSet BasicParts { get ; set ; } } } |
其中BasicParts
是我的实体/模型类,数据类型与数据库中某个表一一对应,内容大概如下:
1 2 3 4 5 6 7 8 9 | using System.ComponentModel.DataAnnotations.Schema; namespace WebApplication1.Models { [Table( "dbo.表名" )] public class BasicParts { // 对应列 } } |
而"name=conn1"
是指使用此数据库配置。该配置在项目根目录下的Web.config中:
2. BasicPartsRepository.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Models { public class BasicPartsRepository { private BasicPartsDbContext _context; public BasicPartsRepository(BasicPartsDbContext context) { _context = context; } public List GetPagedData( int pageIndex, int pageSize) { return _context.BasicParts.OrderBy(i => i.id) .Skip(pageIndex * pageSize) .Take(pageSize) .ToList(); } } } |
控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class HomeController : Controller { private BasicPartsRepository _basicPartsRepository; ... public ActionResult BasicPartsView() { return View(); } [HttpGet] public JsonResult LoadMoreBasicParts( int pageIndex, int pageSize) { var data = _basicPartsRepository.GetPagedData(pageIndex, pageSize); return Json(data, JsonRequestBehavior.AllowGet); } ... } |
前端页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <title>Load More Data Example</title><div id= "data-container" > </div> <button id= "load-more" >加载更多</button> var pageIndex = 0; var pageSize = 20; function loadMoreData() { $.ajax({ url: '/Home/LoadMoreBasicParts' , data: { pageIndex: pageIndex, pageSize: pageSize }, success: function (data) { pageIndex++; // 将新加载的数据追加到页面上 data.forEach( function (item) { $( '#data-container' ).append( '<p>' + item.name + '' ); }); } }); } $(document).ready( function () { $( '#load-more' ).on( 'click' , function () { loadMoreData(); }); // 页面加载完成时,加载初始数据 loadMoreData(); }); </p> |
加载到表格版
其他部分保持不变,只修改前端:
1 | < title >Load More Data into Table</ title > |
No. | 名称 | 序列 | 描述 | 类型 |
---|
var pageIndex = 0;
var pageSize = 20;
function loadMoreData() {
$.ajax({
url: ‘/Home/LoadMoreBasicParts’,
data: {
pageIndex: pageIndex,
pageSize: pageSize
},
success: function (data) {
pageIndex++;
// 将新加载的数据追加到表格中
data.forEach(function (item) {
$(‘#data-table tbody’).append(
‘
‘ ‘ + item.id + ” +
‘ ‘ + item.name + ” +
‘ ‘ + item.seq + ” +
‘ ‘ + item.info + ” +
‘ ‘ + item.stype + ” +
”
);
});
}
});
}
$(document).ready(function () {
$(‘#load-more’).on(‘click’, function () {
loadMoreData();
});
// 页面加载完成时,加载初始数据
loadMoreData();
});
到此这篇关于ASP.NET MVC-懒加载-逐步加载数据库信息的文章就介绍到这了,更多相关ASP.NET MVC逐步加载数据库信息内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!