標籤:cPage style blog color io os 使用 ar for
第三講是應用於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 = 10; public ActionResult Index(int pageIndex=1) { 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})
這個名字是一樣的
ASP.NET的分頁方法(三)