ASP.NET MVC+Unobtrusive Ajax+jQuery实现无刷新分页

一、准备工作
阅读本文前,请您自备瓜子、准备鼠标,学习或复习以下知识:
1、Unobtrusive Ajax(jquery.unobtrusive)
2、ASP.NET MVC基础知识
二、借鉴项目
1、jPaginate
jPaginate 的样式完全符合我的需要,但是它的使用原理是帮您生成分页代码,您只需自定义分页回调函数,这在使用JSON作为返回数据的项目中当然很好用,可惜俺现在执迷的是Unobtrusive Ajax,也就是无需额外代码,通过读取链接元素的属性自动生成异步调用,因此jPaginate在此可谓心有余而力不足啦。
先说说我的实现方法:在服务器端生成分页数据,在客户端通过JS对数据进行美化排版,仅此而已。先看看效果吧:

首页<<
>>末页
三、服务器端工作
需要的类:
1 public class PagingInfo 2 { 3 public int TotalItems { get; set; } 4 public int ItemsPerPage { get; set; } 5 public int CurrentPage { get; set; } 6 7 public int TotalPages 8 { 9 get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); } 10 } 11 }
Action:
1 public ViewResult List(int page=1) 2 { 3 var users = _repository.Users 4 .OrderByDescending(x => x.UserID) 5 .Skip((page - 1) * PageSize) 6 .Take(PageSize); 7 Session["PagingInfo"] = new PagingInfo() 8 { 9 TotalItems = _repository.Users.Count(), 10 CurrentPage = page, 11 ItemsPerPage = PageSize 12 }; 13 return View(users); 14 }
简要说明:这里直接截取了一个小项目中的代码,分页信息通过Session传递到View,你当然可以改成强类型。这个Action只需加载一次,只有当你的数据发生变化(增加、删除)才需重新加载。
View:
@if (Session["PagingInfo"] != null) { class="pager"> @Html.AjaxPageLinks((PagingInfo)Session["PagingInfo"], x => Url.Action("List", new { page = x }),3, "user-list")
}
AjaxPageLinks:
辅助生成Unobtrusive Ajax格式的分页链接。
1 public static class PagingHelpers 2 { 3 /// 4 /// 生成Unobtrusive Ajax action link分页 5 /// 6 ///
7 /// 分页信息
8 /// 生成链接委托
9 /// 页面数量超过该数则生成“首页”“尾页”
10 /// 回调更新的页面元素id
11 /// 12 public static MvcHtmlString AjaxPageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func pageUrl,int leastCountToGenerateFirstLast, string updateTargetId) 13 { 14 StringBuilder result = new StringBuilder(); 15 16 for (int i = 1; i <= pagingInfo.TotalPages; i++) 17 { 18 if (i == 1 && pagingInfo.TotalPages >= leastCountToGenerateFirstLast) 19 { 20 result.Append(CreateAjaxLinkTag("首页", i, pageUrl, updateTargetId, null, "pagination-first").ToString()); 21 result.Append(@"<<"); 22 } 23 24 if (i == 1) 25 { 26 result.Append(@""); 27 result.Append(@"
    "); 28 } 29 30 result.Append("
  • "); 31 result.Append(CreateAjaxLinkTag(i.ToString(), i, pageUrl, updateTargetId).ToString()); 32 result.Append("
  • "); 33 34 if (i == pagingInfo.TotalPages) 35 { 36 result.Append("
"); 37 result.Append("
"); 38 } 39 40 if (pagingInfo.TotalPages >= leastCountToGenerateFirstLast && i == pagingInfo.TotalPages) 41 { 42 result.Append(@">>"); 43 result.Append(CreateAjaxLinkTag("末页", i, pageUrl, updateTargetId, null, "pagination-last").ToString()); 44 } 45 } 46 47 return MvcHtmlString.Create(result.ToString()); 48 } 49 50 private static TagBuilder CreateAjaxLinkTag(string innerHtml, int page, Func pageUrl, string updateTargetId, string className = (string)null, string id = (string)null) 51 { 52 TagBuilder tag = new TagBuilder("a"); 53 tag.MergeAttribute("href", pageUrl(page)); 54 tag.MergeAttribute("data-ajax-mode", "replace"); 55 tag.MergeAttribute("data-ajax", "true"); 56 tag.MergeAttribute("data-ajax-update", "#" + updateTargetId); 57 if(!String.IsNullOrEmpty(className)) 58 tag.AddCssClass(className); 59 if (!String.IsNullOrEmpty(id)) 60 tag.MergeAttribute("id", id); 61 tag.InnerHtml = innerHtml; 62 return tag; 63 } 64 }
生成的链接样式:
1
四、客户端工作
1 jQuery.extend({ 2 enablePaging: function () { 3 var container = $("#pagination-ul-container"); 4 if ((typeof container) == 'undefined') 5 return; 6 7 //#pagination-ul-container宽度 8 var ulWidth = 0; 9 //#pagination-div-container宽度 10 var divWith = $("#pagination-div-container").width(); 11 //总页数 12 var count = container.children().length; 13 //单个分页宽度 14 singleWidth = container.children().eq(0).width(); 15 //总宽度 16 ulWidth = singleWidth * count; 17 container.width(ulWidth); 18 //向左偏移最大值 19 var minLeft = -ulWidth + divWith; 20 21 $("#pagination-next").hover(function () { 22 scroll_hover_interval = setInterval(function () { 23 left = container.position().left - 1; 24 if (left < minLeft) 25 left = minLeft; 26 container.css("left", left + "px"); 27 }, 28 20); 29 }, 30 function () { 31 clearInterval(scroll_hover_interval); 32 }).mousedown(function () { 33 scroll__mouse_interval = setInterval(function () { 34 left = container.position().left - 5; 35 if (left < minLeft) 36 left = minLeft; 37 container.css("left", left + "px"); 38 }, 39 20); 40 }).mouseup(function () { 41 clearInterval(scroll__mouse_interval); 42 }); 43 44 $("#pagination-pre").hover(function () { 45 scroll_hover_interval = setInterval(function () { 46 left = container.position().left + 1; 47 if (left > 0) 48 left = 0; 49 container.css("left", left + "px"); 50 }, 51 20); 52 }, 53 function () { 54 clearInterval(scroll_hover_interval); 55 }).mousedown(function () { 56 scroll__mouse_interval = setInterval(function () { 57 left = container.position().left + 5; 58 if (left > 0) 59 left = 0; 60 container.css("left", left + "px"); 61 }, 62 20); 63 }).mouseup(function () { 64 clearInterval(scroll__mouse_interval); 65 }); 66 67 $("#pagination-first").click(function () { 68 scroll__first_interval = setInterval(function () { 69 left = container.position().left + 5; 70 if (left > 0) { 71 left = 0; 72 container.css("left", left + "px"); 73 clearInterval(scroll__first_interval) 74 } 75 else 76 container.css("left", left + "px"); 77 }, 78 20); 79 }); 80 81 $("#pagination-last").click(function () { 82 scroll__last_interval = setInterval(function () { 83 left = container.position().left - 5; 84 if (left < minLeft) { 85 left = minLeft; 86 container.css("left", left + "px"); 87 clearInterval(scroll__last_interval) 88 } 89 else 90 container.css("left", left + "px"); 91 }, 92 20); 93 }); 94 } 95 })
需要的基本样式:
/* 页面分页 -----------------------------------------------------------*/ .pager{} .pager A{ display:block; padding:0.4em; float:left ;background-color:Yellow; text-decoration:none; cursor:pointer;} .pager A:hover{ background:silver;} .pager DIV#pagination-div-container{ width:73px; height:30px; overflow:hidden;float:left; position:relative;} .pager UL#pagination-ul-container{ height:30px; position:absolute; left:0px;margin:0px;} .pager UL#pagination-ul-container LI{ display:block; float:left;height:30px;} .pager UL#pagination-ul-container LI A{ padding:0.4em 0; width:25px; text-align:center;}

五、完整使用流程
1、Action获取PagingInfo
2、View获取PagingInfo并调用AjaxPageLinks
3、
$(document).ready(function () { $.enablePaging(); });
4、添加基本CSS样式并添加你自己的扩展。
六、结语
花了两天时间做了了这个小玩意,主要是本人对JS并不是很擅长,希望大家多多指教。
Tags: 

延伸阅读

最新评论

发表评论