前段时间整mvc的分页,倒是很顺利,参考了以下几篇博客,启发很大。

http://www.cnblogs.com/tangmingjun/archive/2012/05/30/2526301.html

http://www.cnblogs.com/tangmingjun/archive/2012/05/31/2528732.html

顺便扩展了需求,在分页的基础上,继续做关键字查询。

用PagedList生成的页码链接虽然样式很漂亮,但是要做到无刷新的分页,PagedList自动生成的代码是不够用的,可以配合jsRender和Ajax做上面的效果,同时手动构建PagedList生成的页码标签,根据自己的需要设置href和onclick事件。

直接上代码

前台:

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
} <h2>商品信息</h2> <p>
@Html.ActionLink("新建", "Create") |
@Html.Editor("txtSearch")
<input type="button" value="查找" id="btnSearch" />
<img id="imgWaiting" src="~/Images/loading.gif" style="display:none; width:30px; height:30px;" />
</p>
<table class="table">
<thead>
<tr>
<th>商品名称</th>
<th>商品描述</th>
<th>原价</th>
<th>特价(现价)</th>
<th>销量</th>
<th>修改日期</th>
<th>商品链接</th>
<th>状态</th>
<th>图片</th>
<th></th>
</tr>
</thead>
<tbody id="tblContent"></tbody>
</table>
<div id="divPage"></div> <script type="text/x-jsrender" id="contentTemplate">
<tr>
<td>{{:GoodName}}</td>
<td>{{:Description}}</td>
<td>{{:OriginalPrice}}</td>
<td>{{:SpecialPrice}}</td>
<td>{{:Sales}}</td>
<td>{{:ActiveTime}}</td>
<td>{{:Url}}</td>
<td>{{:Status}}</td>
<td>{{:PicPath}}@*<img id="PicPath" src="{{:PicPath}}" class="thumbnailPdt" />*@</td>
<td>
<a href="/Admin/Goods/Edit/{{:GoodID}}">Edit</a> |
<a href="/Admin/Goods/Delete/{{:GoodID}}">Delete</a>
</td>
</tr>
</script> @section Scripts{
<script src="~/Scripts/jsrender.min.js" type="text/javascript"></script>
<script>
var key = "";
function doSearch(page) {
key = $("#txtSearch").val();
$.post(
"/Admin/Goods/SearchProduct",
{ keyword: key, pageNo: page },
function (data, status) {
//数据写到前台
$("#tblContent").html($("#contentTemplate").render(data.contents));
$("#divPage").html(data["pageList"]);
},
"json"
);
};
//绑定点击查询事件
$("#btnSearch").click(function () {
doSearch(1);
});
//输入框回车开始查询
$("#txtFilter").bind("keypress", function () {
if (event.keyCode == 13) { $("#btnSearch").click(); return false; }
});
//加载初始化数据
$(function () {
doSearch(1);
});
</script>
}

后台Controller:

public ActionResult Index()
{
return View();
} public JsonResult SearchProduct(string keyword, int? pageNo)
{
int pageIndex = pageNo ?? ;
int totalCount;
var goods = GetSearchData(keyword, ref pageIndex, _PageSize, out totalCount);
int totalPage = totalCount / _PageSize + (totalCount % _PageSize == ? : );
var pagerHtml = ExHtml.CreatePagesHtml(totalPage, pageIndex); return Json(new { contents = goods, pageList = pagerHtml }, JsonRequestBehavior.DenyGet);
} List<Good> GetSearchData(string keyword, ref int pageIndex, int pageSize, out int totalCount)
{
var linq = from p in db.Goods select p;
if (!string.IsNullOrWhiteSpace(keyword))
{
linq = linq.Where(t =>
t.GoodID.ToString() == keyword
|| t.GoodName.Contains(keyword)
|| t.Description.Contains(keyword)
);
}
totalCount = linq.Count();
//修正pageIndex
var maxPage = totalCount / pageSize + (totalCount % pageSize == ? : );
if (pageIndex < ) pageIndex = ;
if (pageIndex > maxPage) pageIndex = maxPage;
linq = linq.OrderByDescending(x => x.GoodID)
.Skip((pageIndex - ) * pageSize)
.Take(pageSize); return linq.ToList();
}

扩展函数:

public static string CreatePagesHtml(int totalPageNo, int currPageNo, string jsClickName = "doSearch")
{
if (currPageNo > totalPageNo || currPageNo < || totalPageNo == ) return "";
string res = "";
if (currPageNo > ) res += LiForFirst(jsClickName);//有跳转到第一页
//if (currPageNo > 2) res += LiForPrev(currPageNo - 1, jsClickName);//跳转到前一页
if (currPageNo > ) res += LiForOthers();//无跳转,显示中间有页面
if (currPageNo > ) res += LiForPage(currPageNo - , jsClickName);//前两页
if (currPageNo > ) res += LiForPage(currPageNo - , jsClickName);//前一页 res += LiForCurr(currPageNo);//当前页 if (currPageNo < totalPageNo) res += LiForPage(currPageNo + , jsClickName);//下一页
if (currPageNo < totalPageNo - ) res += LiForPage(currPageNo + , jsClickName);//下两页
if (currPageNo < totalPageNo - ) res += LiForOthers();//无跳转,显示中间有页面
//if (currPageNo < totalPageNo - 1) res += LiForNext(currPageNo + 1, jsClickName);//跳转到后一页
if (currPageNo < totalPageNo - ) res += LiForLast(totalPageNo, jsClickName);//跳转到最后页
return string.Format(@"
<div class=""pagination-container"">
<ul class=""pagination"">
{0}
</ul>
</div>"
, res);
}
static string GetPageItem(int pageNo, string text, string jsClickName, string classStr = null, string rel = null)
{
return string.Format(@"<li{0}><a href=""#""{1}{2}>{3}</a></li>"
, string.IsNullOrWhiteSpace(classStr) ? "" : " class=\"" + classStr + "\""
, string.IsNullOrWhiteSpace(rel) ? "" : " rel=\"" + rel + "\""
, string.IsNullOrWhiteSpace(jsClickName) ? "" : string.Format(" onclick=\"{0}({1});\"", jsClickName, pageNo)
, text
);
}
static string LiForFirst(string jsClickName) { return GetPageItem(, ""/*"««"*/, jsClickName, classStr: "PagedList-skipToFirst"); }
static string LiForPrev(int pageNo, string jsClickName) { return GetPageItem(pageNo, "«", jsClickName, classStr: "PagedList-skipToPrevious", rel: "prev"); }
static string LiForNext(int pageNo, string jsClickName) { return GetPageItem(pageNo, "»", jsClickName, classStr: "PagedList-skipToNext", rel: "next"); }
static string LiForLast(int totalPageNo, string jsClickName) { return GetPageItem(totalPageNo, totalPageNo.ToString()/*"»»"*/, jsClickName, classStr: "PagedList-skipToLast"); }
static string LiForPage(int pageNo, string jsClickName) { return GetPageItem(pageNo, pageNo.ToString(), jsClickName); }
static string LiForCurr(int pageNo) { return GetPageItem(pageNo, pageNo.ToString(), null, classStr: "active"); }
static string LiForOthers() { return GetPageItem(, "…", null, classStr: "disabled PagedList-ellipses"); }

前台的关键代码是js函数doSearch,通过post发送请求,请求成功后处理返回的json数据,并重新加载页面部分元素。json数据包有两个属性,一个contents,里面是类型为List<T>的数据,通过jsrender的调用,生成前台表格的tbody中的代码;另一个pageList是后台组装好的,显示page按钮的string。

后台Controller代码中,主要是第二个函数SearchProduct,它可以作为一个controller下面的action调用,在里面执行查询数据,以及组装pageHtml的操作,并打包这些数据成json数据,返回给前台。

扩展函数代码则主要是组装page的string结果。这部分参考PagedList生成的页码标签的代码,样式在bootstrap里面都有。

环境:VS2013 + MVC5.0 + Bootstrap 3.0

JsRender下载地址

ASP.NET MVC分页 Ajax+JsRender的更多相关文章

  1. ASP.NET MVC分页组件MvcPager 2.0版发布暨网站全新改版

    MvcPager分页控件是在ASP.NET MVC Web应用程序中实现分页功能的一系列扩展方法,该分页控件的最初的实现方法借鉴了网上流行的部分源代码, 尤其是ScottGu的PagedList< ...

  2. asp.net mvc 使用ajax请求 控制器 (PartialViewResult)分部的action,得到一个分部视图(PartialView)的HTML,进行渲染

    在asp.net mvc 使用ajax请求获取数据的时候,我们一般是返回json或者xml,然后解析这些数据进行渲染,这样会比较麻烦,可以请求一个 分部action,返回一个分部视图 直接可以渲染,不 ...

  3. ASP.NET MVC 实现AJAX跨域请求方法《1》

    ASP.NET MVC 实现AJAX跨域请求的两种方法 通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据 ...

  4. 在Asp.Net MVC中用Ajax回调后台方法

    在Asp.Net MVC中用Ajax回调后台方法基本格式: var operData = ...; //传递的参数(action中定义的) var type = ...; //传递的参数(action ...

  5. ASP.NET MVC分页实现之改进版-增加同一个视图可设置多个分页

    我之前就已经实现了ASP.NET MVC分页(查看该博文),但它有局限性,必须确保在同一个视图中只能有一处分页,若需要在同一个视图中设置多个分页,却无能为力,为此,我重新对原先的代码进行了优化,增加了 ...

  6. [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传

    原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...

  7. 基于Bootstrap的Asp.net Mvc 分页

    基于Bootstrap的Asp.net Mvc 分页的实现 最近写了一个mvc 的 分页,样式是基于 bootstrap 的 ,提供查询条件,不过可以自己写样式根据个人的喜好,以此分享一下.首先新建一 ...

  8. Asp.Net MVC 使用 Ajax

    Asp.Net MVC 使用 Ajax Ajax 简单来说Ajax是一个无需重新加载整个网页的情况下,可以更新局部页面或数据的技术(异步的发送接收数据,不会干扰当前页面). Ajax工作原理 Ajax ...

  9. Asp.Net MVC Unobtrusive Ajax

    1.   Unobtrusive JavaScript介绍 说到Unobtrusive Ajax,就要谈谈UnobtrusiveJavaScript了,所谓Unobtrusive JavaScript ...

随机推荐

  1. JPA的多表复杂查询

    转 JPA的多表复杂查询:详细篇 原文链接: https://mp.weixin.qq.com/s/7J6ANppuiZJccIVN-h0T3Q 2017-11-10 从小爱喝AD钙  最近工作中由于 ...

  2. 重新认识Javascript的一些误区总结

    1.在函数内有没有var真的不一样 下面这样一段代码,在函数abc()中,创建了两个变量a, c,并在函数体之外进行alert,想看看有什么事发生: <script> function a ...

  3. JAVA日期查询:季度、月份、星期等时间信息

    package com.stt.dateChange; import java.text.SimpleDateFormat; import java.util.Calendar; import jav ...

  4. 亿级Web系统搭建:单机到分布式集群【转】

    当一个Web系统从日访问量10万逐步增长到1000万,甚至超过1亿的过程中,Web系统承受的压力会越来越大,在这个过程中,我们会遇到很多的问题.为了解决这些性能压力带来问题,我们需要在Web系统架构层 ...

  5. php分享二十九:命名空间

    1:命名空间的命名不区分大小写 2:namespace必须在所有代码之前,除了declare语法以外(不过他之前可以有注释,空行等) 3:只有以下类型的代码受命名空间的影响,它们是:类(包括抽象类和t ...

  6. linux命令分享一:压缩命令

    Linux操作系统中,*.zip.*.tar.*.tar.gz.*.tar.bz2.*.tar.xz.*.jar.*.7z等格式的压缩与解压 zip格式 压缩: zip -r [目标文件名].zip ...

  7. 用bundler安装jeklly

    为什么要写这篇文章呢?因为官方的安装文档里,ruby的很多库没有说明怎么安装.所以需要重点说明一下.1.我的安装环境是vultr的16.04版的ubuntu.2.因为ruby的扩展库好多都是Gcc编译 ...

  8. Struts2对值的推断

    目的是想将jsp中的input输入: <input class="inputstyle" type="text" value="<s:pr ...

  9. HTML5学习笔记(二十六):JavaScript的错误处理

    错误相关的调试和处理在开发中是特别重要的一种技能. try-catch 我们来看下面的情况: // noneFunc 这个方法并不存在 window.noneFunc(); // js 报错后终止运行 ...

  10. spark-architecture

    https://0x0fff.com/spark-architecture-shuffle/ https://0x0fff.com/spark-memory-management/ https://0 ...