• ASP.NET MVC轻教程 Step By Step 9——分页


    现在我们要把Index视图的留言信息进行分页显示。

    Step 1. 创建路由

    我们希望以类似地址http://localhost:41583/Page1来表示第一页,Page2表示第二页,以此类推。在RouteConfig.cs中已有一条默认路由,但不能满足匹配类似/Page1这样的URL。我们要添加一条新的路由规则。

            public static void RegisterRoutes(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. 修改Index动作方法

            public ActionResult Index(int page=1)
            {
                int pagesize = 3;
                ViewBag.Page = page;
                ViewBag.TotalPages = Math.Ceiling((double)messages.Count / pagesize);
                return View(messages.Skip((page-1)*pagesize).Take(pagesize).OrderByDescending(v=>v.ReleaseDate));
            }

    Index动作方法做了很多修改补充。page参数与路由规则中的{page}相对应,设置了其默认值为1,这样页面首先展示第一页。pagesize设定每页显示留言数量,通过ViewBag把当前页和总页数传递给Index视图。

    Step 3. 修改Index视图

    <body>
        <h1>MVC留言板</h1>
        @Html.ActionLink("我要留言", "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("上一页", "Index", new { page = ViewBag.Page - 1 })
        }
        @if (ViewBag.Page < ViewBag.TotalPages)
        {
            @Html.ActionLink("下一页", "Index", new { page = ViewBag.Page + 1 })
        }
    <body>

    通过当前页和总页数来有选择的生成超链接。现在我们可以看到成果了。

    这个分页当然非常地简陋,有很多改进的余地。如果想把分页做得更美观、功能更强大,可以参考这我的一篇《Asp.net MVC分页实例》。

  • 相关阅读:
    websocket协议解决消息发送问题 Could not decode a text frame as UTF-8.
    成功解决internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'minimatch'
    FastDFS客户端与自定义文件存储系统
    fastdfs 中client.conf 文件
    centos 中 redis 的安装
    redis安装成功后get: command not found
    Shell基础知识(二)
    Shell基础知识(一)
    binary search模板总结
    配置远程jupyter notebook
  • 原文地址:https://www.cnblogs.com/nivi3000/p/4970086.html
Copyright © 2020-2023  润新知