文章的顯示都是通過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>