ASP.NET MVC 2入门演练 6 —— 分页查询数据
这里只是把List改造了一下。
1、在List.aspx 的列表上方加了如下代码:
<form id="frmCreate" action="<%=Url.Action("List","News")%>" method="post">
<%: Html.DropDownListFor(m => new CMSNews().NewsCategory, new SelectList(new MVC2Demo.Models.MVCDemoEntities().CMSNewsCategory.ToList(),
"CategoryCode", "CategoryName"),"==Select==")%>
<input type="submit" value="Search" />
<%: Html.DropDownListFor(m => new CMSNews().NewsCategory, new SelectList(new MVC2Demo.Models.MVCDemoEntities().CMSNewsCategory.ToList(),
"CategoryCode", "CategoryName"),"==Select==")%>
<input type="submit" value="Search" />
</form>
2、修改List.aspx中的分页代码
<div class="pager">
<%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, "List", new { NewsCategory = ViewData["Category"] })%>
</div>
<%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, "List", new { NewsCategory = ViewData["Category"] })%>
</div>
List是NewsController中的Action,new { NewsCategory = ViewData["Category"] }是List这个Action中对应的参数NewsCategory的赋值,也就是说我将List这个Action也修改了一下,多加了一个参数NewsCategory ,所以再多加参数,只需要在new后面的大括号中加就行,用“,”间隔,这应该就是C#3.0中的对象初始化器。
3、修改NewsController的List这个Action
/// <summary>
/// List
/// 写的比较仓促,读者根据需要修改
/// </summary>
/// <param name="page">页码</param>
/// <param name="NewsCategory">跟前台DropDownList的ID是同名的,也就是这里<%: Html.DropDownListFor(m => new CMSNews().NewsCategory</param>
/// <returns></returns>
public ActionResult List(int? page, String NewsCategory)
{
//用ViewData["Category"]存储DropDownList选中项的值
ViewData["Category"] = NewsCategory;
//每页显示的记录数
const int defaultPageSize = 1;
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if(!String.IsNullOrEmpty(NewsCategory))
{
return View(db.CMSNews.Where(Model => Model.NewsCategory == NewsCategory).OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
}
else
{
return View(db.CMSNews.OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
}
}
/// List
/// 写的比较仓促,读者根据需要修改
/// </summary>
/// <param name="page">页码</param>
/// <param name="NewsCategory">跟前台DropDownList的ID是同名的,也就是这里<%: Html.DropDownListFor(m => new CMSNews().NewsCategory</param>
/// <returns></returns>
public ActionResult List(int? page, String NewsCategory)
{
//用ViewData["Category"]存储DropDownList选中项的值
ViewData["Category"] = NewsCategory;
//每页显示的记录数
const int defaultPageSize = 1;
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if(!String.IsNullOrEmpty(NewsCategory))
{
return View(db.CMSNews.Where(Model => Model.NewsCategory == NewsCategory).OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
}
else
{
return View(db.CMSNews.OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
}
}
这里用ViewData["Category"]来保存DropDownList中选中项的值,由于MVCPaging是用Url来翻页,如果不这样做,将无法保持DropDownList选中项的值,或者还有其他方法,暂时还没研究到。