asp.net MVC实现文章的“上一篇下一篇”

由于这个东西的原理没有什么难的(只是实现的时候有少量的坑),故直接上代码以便查阅。另:本文给出的Action附送了点击量统计。

public ActionResult SingleNews(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var news = storeDB.articles.Find(id);

            var prev = storeDB.articles.Where(p => p.ID<id).OrderByDescending(p => p.ID).Take(1).ToList();
            var next = storeDB.articles.Where(p => p.ID>id).Take(1).ToList();
            
            if(prev.Count>0)
            {
                ViewBag.preTitle = prev.ElementAt(0).title;
                ViewBag.preId = prev.ElementAt(0).ID;
            }
            else
            {
                ViewBag.preTitle = "没有了";
                ViewBag.preId = id;
            }

            if (next.Count>0)
            {
                ViewBag.nextTitle = next.ElementAt(0).title;
                ViewBag.nextId = next.ElementAt(0).ID;
            }
            else
            {
                ViewBag.nextTitle = "没有了";
                ViewBag.nextId = id;
            }
            
            //记录点击量
            if(news!=null)
            {
                news.clickCount += 1;
                storeDB.Entry(news).State = EntityState.Modified;
                storeDB.SaveChanges();    
            }
            
            return View(news);
        }

视图中的相关代码:

<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>

本文参考了下面这篇文章并在此基础上做了改进:http://www.cnblogs.com/denny402/p/3215384.html

转载于:https://www.cnblogs.com/eternalwt/p/3678719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值