接上篇mvc3 分页Helper.

  带查询的分页Helper是在上一篇分页的基础上来的。下面看代码:

  首先,在System.Web.Mvc命名空间下的自定义类HtmlPage下面添加一个用于处理“查询字典”的方法UrlGetParameter。  

  

 /// <summary>
/// 根据查询字典,拼写查询参数
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public static string UrlGetParameter(Dictionary<string,string> parameters)
{
if (parameters != null && parameters.Count > )
{
StringBuilder sb = new StringBuilder();
foreach (var item in parameters)
{
sb.Append("&"+item.Key.ToLower()+"="+item.Value);
}
return sb.ToString();
}
else
{
return "";
}
}

UrlGetParameter方法

  然后,修改HtmlPage类下面的ShowPageNavigate方法如下:

  

  public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount,Dictionary<string,string> parameters=null)
{
var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
pageSize = pageSize == ? : pageSize;
var totalPages = Math.Max((totalCount + pageSize - ) / pageSize, ); //总页数
string searchCode = string.Empty;
if (parameters!=null)
{
searchCode = UrlGetParameter(parameters);
}
var output = new StringBuilder();
if (totalPages > )
{
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}{2}'>首页</a> ", redirectTo, pageSize,searchCode);
if (currentPage > )
{//处理上一页的连接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>上一页</a> ", redirectTo, currentPage - , pageSize,searchCode);
} output.Append(" ");
int currint = ;
for (int i = ; i <= ; i++)
{//一共最多显示10个页码,前面5个,后面5个
if ((currentPage + i - currint) >= && (currentPage + i - currint) <= totalPages)
{
if (currint == i)
{//当前页处理
output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}{3}'>{4}</a> ", redirectTo, currentPage, pageSize, searchCode, currentPage);
}
else
{//一般页处理
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{4}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint,searchCode);
}
}
output.Append(" ");
}
if (currentPage < totalPages)
{//处理下一页的链接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>下一页</a> ", redirectTo, currentPage + , pageSize,searchCode);
} output.Append(" ");
if (currentPage != totalPages)
{
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>末页</a> ", redirectTo, totalPages, pageSize,searchCode);
}
output.Append(" ");
}
output.AppendFormat("<label>第{0}页 / 共{1}页</label>", currentPage, totalPages);//这个统计加不加都行 return new HtmlString(output.ToString());
}

ShowPageNavigate方法

  其次,还要将"查询字典"属性添加到PageInfo字典中。  

  

 public class PagerInfo
{
public int RecordCount { get; set; } public int CurrentPageIndex { get; set; } public int PageSize { get; set; }
//放置查询参数
public Dictionary<string, string> SearchParameter { get; set; }
}

PageInfo类

  最后,就要写View和Controller里的内容的。先看Controller的代码,添加一个用于回发的Action即(Index),把get,post的Action都写出来吧。

  

 //get /News/Index/?
public ActionResult Index(int? pageSize, int? pageIndex, string pauthor, string ptitle)
{
Dictionary<string, string> pagerParamers = new Dictionary<string, string>();
int pageIndex1 = pageIndex ?? ;
int pageSize1 = pageSize ?? ;
//从数据库在取得数据,并返回总记录数
var temp = newsSer.LoadEntities(c => c.del == false).AsQueryable();
PagerInfo pager = new PagerInfo();
pager.CurrentPageIndex = pageIndex1;
pager.PageSize = pageSize1;
if (!string.IsNullOrEmpty(pauthor))
{
pagerParamers.Add("pauthor", pauthor);
temp = temp.Where(c => c.author.Contains(pauthor)).AsQueryable();
}
if (!string.IsNullOrEmpty(ptitle))
{
pagerParamers.Add("ptitle", ptitle);
temp=temp.Where(c => c.title.Contains(ptitle)).AsQueryable();
}
pager.RecordCount = temp.Count();
pager.SearchParameter = pagerParamers;
temp=temp.OrderByDescending(c => c.id).Skip((pageIndex1 - ) * pageSize1).Take(pageSize1).AsQueryable();
PagerQuery<PagerInfo, IQueryable<news>> query = new PagerQuery<PagerInfo, IQueryable<news>>(pager, temp);
return View(query);
} //Post /News/Index/?
[HttpPost]
public ActionResult Index(FormCollection form)
{
try
{
string pauthor = form["pauthor"];
string ptitle = form["ptitle"];
Dictionary<string, string> pagerParams = new Dictionary<string, string>();
int pageIndex = ;
int pageSize = ;
PagerInfo pager = new PagerInfo();
pager.CurrentPageIndex = pageIndex;
pager.PageSize = pageSize;
//从数据库在取得数据,并返回总记录数
var temp = newsSer.LoadEntities(c => c.author.Contains(pauthor)).AsQueryable();
if (!string.IsNullOrEmpty(pauthor))
{
pagerParams.Add("pauthor", pauthor);
temp = temp.Where(c => c.author.Contains(pauthor) && c.del == false).AsQueryable();
}
if (!string.IsNullOrEmpty(ptitle))
{
pagerParams.Add("ptitle", ptitle);
temp = temp.Where(c => c.title.Contains(ptitle)).AsQueryable();
}
pager.RecordCount = temp.Count();
pager.SearchParameter = pagerParams;
temp = temp.OrderBy(c => c.id).Skip((pageIndex - ) * pageSize).Take(pageSize);
PagerQuery<PagerInfo, IQueryable<news>> query = new PagerQuery<PagerInfo, IQueryable<news>>(pager, temp);
return View(query);
}
catch
{
return View();
}
}

Action (Index)

  接下来,看一下View中的代码:  

  

  @using (Html.BeginForm("Index", "News", FormMethod.Post, new { @class = "well" }))
{
<input type="text" id="pauthor" class="search-query" name="pauthor" placeholder="作者" />
<input type="text" id="ptitle" class="search-query" name="ptitle" placeholder="标题" />
<input type="submit" class="btn" value="查询" />
}
<table style="margin-top: 10px;">
<thead>
<tr>
<th width="25">
<input class="select-all" name="" type="checkbox" value="" />
</th>
<th>
作者
</th>
<th>
新闻标题
</th>
<th>
创建时间
</th>
<th>
操作
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.EntityList)
{
<tr>
<td class="checkBox">
<input name="ids[]" type="checkbox" value="" />
</td>
<td>
@item.author
</td>
<td>
@item.title
</td>
<td>
@item.ctime
</td>
<td>
@Html.ActionLink("编辑", "Edit", new { id = item.id }) |
@Html.ActionLink("删除", "Delete", new { id = item.id })
</td>
</tr>
}
@*分页*@
<tr class="">
<td colspan="5" align="center" class="paginator">
<span>
@Html.ShowPageNavigate(Model.Pager.CurrentPageIndex, Model.Pager.PageSize, Model.Pager.RecordCount, Model.Pager.SearchParameter)
</span>
</td>
</tr>
</tbody>
</table>

  分页的样式见上一节"MVC# 分页Helper",查询表单的样式,就不再列出了。

  最后再补充一下,如果在查询时依然想要使用以前的PageSize(当然了,这里的PageSize是固定的),可以在进行请求时将pageSize保存在ViewBag中,然后在View中将它保存在表单的隐藏域中,这样就可以使用设置好的pageSize了。(页面跳转、上n页、下n页,这里就不列出来了。)

  最终的效果图:  

  

  ok.大功告成!

MVC3 带查询的分页Helper的更多相关文章

  1. 关于ExtJs4的Grid带 查询 参数 分页(baseParams-->extraParams)

    (园里很多文章,美名其曰 :ExtJs GridPanel+查询条件+分页.  但是加查询条件后点击下一页,查询条件失效,求你们自己测试明白再显摆 不要误导我这种新人.) ExtJs6发布了,ExtJ ...

  2. Java高级架构师(一)第15节:带查询的分页、修改和删除页面

    @RequestMapping(value="toList",method=RequestMethod.GET) public String toList(@ModelAttrib ...

  3. mysq带条件的分页查询数据结果错误

    记一次mysql分页条件查询的结果出错: 以一张用户表为例,首先我们看表中的所有数据,注意红色框住的部分: 我们使用不带条件的分页查询来查询,数据显示是OK的: SELECT id,login_nam ...

  4. hibernate中带查询条件的分页

    所谓分页,从数据库中分,则是封装一个分页类.利用分页对象进行分页. 但,分页往往带查询条件. 分页类的三个重要数据:[当前页码数],[数据库中的总记录数],[每页显示的数据的条数] 原理:select ...

  5. laravel 带条件的分页查询

    laravel 带条件的分页查询, 原文:http://blog.csdn.net/u011020900/article/details/52369094 bug:断点查询,点击分页,查询条件消失. ...

  6. webform组合查询和分页

    1.组合查询(1)数据访问类 //参数1:SQL语句 参数2:哈希表public List<Users> chas(string s,Hashtable has) { List<Us ...

  7. 使用插件bootstrap-table实现表格记录的查询、分页、排序等处理

    在业务系统开发中,对表格记录的查询.分页.排序等处理是非常常见的,在Web开发中,可以采用很多功能强大的插件来满足要求,且能极大的提高开发效率,本随笔介绍这个bootstrap-table是一款非常有 ...

  8. SQL Server -- 回忆笔记(四):case函数,索引,子查询,分页查询,视图,存储过程

    SQL Server知识点回忆篇(四):case函数,索引,子查询,分页查询,视图,存储过程 1. CASE函数(相当于C#中的Switch) then '未成年人' else '成年人' end f ...

  9. 基于Metronic的Bootstrap开发框架经验总结(16)-- 使用插件bootstrap-table实现表格记录的查询、分页、排序等处理

    在业务系统开发中,对表格记录的查询.分页.排序等处理是非常常见的,在Web开发中,可以采用很多功能强大的插件来满足要求,且能极大的提高开发效率,本随笔介绍这个bootstrap-table是一款非常有 ...

随机推荐

  1. 利用SQL语句产生分组序号

    partition  by关键字是分析性函数的一部分,它和聚合函数不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录,partition  by用于给结果集分组,如果没 ...

  2. 【noip2012提高组】国王游戏

    恰逢 H 国国庆,国王邀请 n 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右 手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 n 位大臣排 成一排,国王站在队伍的最前面. ...

  3. not valid for Running the scheme

    The run destination iPhone6 Plus is not valid for Running the scheme 'MyApp’. Phone6 Plus's iOS 8.0 ...

  4. 各种HelloWorld

    http://blog.csdn.net/whxaing2011/article/details/20736759 ES总结: http://www.cnblogs.com/sunxucool/p/3 ...

  5. MATLAB介绍

    MATLAB MATLAB[1]  是美国MathWorks公司出品的商业数学软件,用于算法开发.数据可视化.数据分析以及数值计算的高级技术计算语言和交互式环境,主要包括MATLAB和Simulink ...

  6. 传智播客C/C++学员荣膺微软&Cocos 2d-x黑客松最佳创新奖

     6月30日,历时32小时的微软开放技术Cocos 2d-x 编程黑客松在北京望京微软大厦成功落下帷幕,这是微软开放技术首次联合Cocos 2d-x 在中国举办黑客松.此次活动共有包括传智播客C/ ...

  7. poj3085

    #include <stdio.h> #include <stdlib.h> int main() { ; scanf("%d",&n); whil ...

  8. Qt开发初步,循序渐进,preRequest for 蓝图逆袭

    1,使用Qt面向对象类继承创建第一个窗口主部件,使用setMinimumSize(),setMaximumSize()配置主部件窗口是否能够resize;

  9. debian安装jdk6

    一般用命令 apt-get install sun-java6-jdk ,会报找不到源的错误. vim /etc/apt/sources.list # 於最下方新增此行 deb http://ftp. ...

  10. Android UI ActionBar功能-自定义Tab功能

    还可以使用ActionBar实现Tab选项卡功能: 官方帮助文档:http://wear.techbrood.com/training/basics/actionbar/styling.html#Cu ...