ASP.NET的分页方法(三)

时间:2023-03-09 01:53:08
ASP.NET的分页方法(三)

第三讲是应用于MVC上面的分页,很多时候MVC要和EF表达式一起使用,但是我这个使用的最原始的ADO.NET,一样实现了这个效果。要实现这个效果首先要得到MvcPager.dll,引用之后,前台操作如下:

@using Webdiyer.WebControls.Mvc;
@model PagedList<MVCTest.Models.Info>
<!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@foreach (MVCTest.Models.Info info in ViewBag.Content)
{
<span>@info.Title</span><br />
} @Html.Pager(Model,new PagerOptions{PageIndexParameterName = "pageIndex",ShowPageIndexBox = true,PageIndexBoxType = PageIndexBoxType.DropDownList,ShowGoButton = false})
@section Scripts{@{Html.RegisterMvcPagerScriptResource();}}
</body>
</html>

这里前台需要引用Webdiyer.WebControls.Mvc;这个空间,并且要引用一下PagerList这个集合,里面包括着你要显示数据的类。例如PagedList<MVCTest.Models.Info>

后台的写法如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest.Models;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using Webdiyer.WebControls.Mvc;
namespace MVCTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/ int pageSize = ; public ActionResult Index(int pageIndex=)
{ string GetDateSql = "SELECT * FROM [Info]"; string ConStr = ConfigurationManager.ConnectionStrings["Connection"].ToString(); using (SqlConnection conn = new SqlConnection(ConStr))
{
conn.Open();
SqlCommand comm = new SqlCommand(GetDateSql, conn); SqlDataReader reader = comm.ExecuteReader();
List<Info> infoItem = new List<Info>();
while (reader.Read())
{
Info info = new Info();
info.Title = reader["Title"].ToString();
infoItem.Add(info);
}
reader.Close();
PagedList<Info> list = infoItem.ToPagedList(pageIndex, pageSize);
ViewBag.Content = list;
return View(list);
}
}
}
}

对于后台, 也要引用using Webdiyer.WebControls.Mvc;这个类,之后可以把使用SqlDataReader读出的数据,放入一个泛型集合,然后在

PagedList<Info> list = infoItem.ToPagedList(pageIndex, pageSize);这一步的时候转换为pagerlist并且使用return view把pagerlist的内容返回到视图层,这里要注意的是,前台绑定的数据源要和分页所使用的数据源为同一个数据源,为pagerlist的这个数据源
 PagedList<Info> list = infoItem.ToPagedList(pageIndex, pageSize);
ViewBag.Content = list;
return View(list);
在控制器里面需传递一个参数,就是当前页索引
pageIndex,这个参数默认为1,它的名字要和前台的
@Html.Pager(Model,new PagerOptions{PageIndexParameterName = "pageIndex",ShowPageIndexBox = true,PageIndexBoxType = PageIndexBoxType.DropDownList,ShowGoButton = false})
这个名字是一样的