MVC3学习:实现文章上一篇下一篇链接

文章的显示都是通过id查询数据库来显示。但是文章会经常删除,因此id号可能不是连续的,所以上一篇下一篇文章,不能简单的做id加减法。

我的思路是:先将表格中所有文章的ID号全部放入一个数组中,如果文章比较多,也可以分类操作。然后通过循环数组找出上一篇下一篇文章的ID号。有了ID号,文章自然而然的就找到了。

假设文章表名为News,主键为id,标题为title:

直接上图:Controller

public ActionResult NewsContent(int? id)
        {
            //用pre和next变量分别存放上一篇文章和下一篇文章的id号
            int pre = 0, next = 0, i = 0, j;
            //计算总记录数
            int num = db.News.Count();
            int[] a = new int[num];
            var query = from c in db.News.select c.id;
            //将所有的文章id号全部放入一个数组中
            foreach (var item in query)
            {
                a[i] = Convert.ToInt32(item);
                i++;
            }
            //循环,获取上一篇和下一篇文章的ID号,分别放入变量pre和next中
            for (j = 0; j < num; j++)
            {
                if (a[j] == id)
                {
                    if (j != 0) pre = a[j - 1];
                    if (j != num - 1) next = a[j + 1];
                }
            }
            //获取上一篇文章的标题
            if (pre == 0)
            {
                ViewBag.preTitle = "没有了";
                ViewBag.pre = id;
            }
            else
            {
                ViewBag.preTitle = db.News.Where(c => c.id == pre).Single().Title;
                ViewBag.pre = pre;
            }
            //获取下一篇文章的标题
            if (next == 0)
            {
                ViewBag.nextTitle = "没有了";
                ViewBag.next = id;
            }
            else
            {
                ViewBag.nextTitle = db.News.Where(c => c.id == next).Single().Title;
                ViewBag.next = next;
            }
News n
= db.News.Where(c => c.id == id).Single(); return View(n); }

不仅仅是asp.net mvc可以这样做,asp.net也可以,原理是一样的。

在视图中:NewsContent

 <div>
  <label>上一篇:</label>@Html.ActionLink((string)ViewBag.preTitle, "NewsContent", new { id=ViewBag.pre})
  <label>下一篇:</label>@Html.ActionLink((string)ViewBag.nextTitle, "NewsContent", new { id=ViewBag.next})
  </div>
原文地址:https://www.cnblogs.com/denny402/p/3215384.html