Now we are going to display the message of the index view in pagination.
Step 1. Create a route
We want to represent the first page with similar address Http://localhost:41583/Page1, Page2 represents the second page, and so on. There is already a default route in RouteConfig.cs, but it does not match URLs similar to/page1. We're going to add a new routing rule.
Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); routes. MapRoute (name: "Index", url: "page{page}", Defaults: new {controller = "Home", action = "Index " } ); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}); }
Step 2. Modify the Index action method
Public ActionResult Index (int page=1) { int3; = page; = Math.ceiling (double) messages. Count/ pagesize); return View (Messages. Skip ((page-1) *pagesize). Take (pagesize)); }
The index action method has been supplemented by many modifications. The page parameter corresponds to {page} in the routing rule and sets its default value to 1, so that the first page is displayed first. PageSize set the number of messages per page and pass viewbag the current page and total pages to the index view.
Step 3. Modify the Index view
<Body> <H1>MVC Message Board</H1>@Html. ActionLink ("I want to leave a message", "Write") @foreach (Var message in Model) {<P>@message. Nickname</P> <P>@message. Content</P> <P>@message. ReleaseDate</P> <BR/>} @if (Viewbag.page > 1) {@Html. ActionLink ("Previous page", "Index", new {page = viewbag.page-1}) } @if (Viewbag.page < Viewbag.totalpages) {@Html. ActionLink ("Next page", "Index", new {page = Viewbag.page + 1})}
<body>
Generate hyperlinks that are selected by the current page and the total number of pages. Now we can see the results.
This paging is, of course, very primitive, with plenty of room for improvement. If you want to make the paging more beautiful, more powerful, you can refer to this one of my "ASP. NET MVC pagination instance."
ASP. NET MVC Light Tutorial Step by Step 9--pagination