paginate forum posts

This commit is contained in:
Michael 2017-04-20 09:20:05 -04:00
parent d3935e31b5
commit f5c33c367a
2 changed files with 45 additions and 3 deletions

View file

@ -318,9 +318,13 @@ public ActionResult MarkRead(string id)
return RedirectToAction("ViewUnread");
}
[Authorize]
public ActionResult ViewTopic(string id, bool triedtolikeowntopic = false)
public ActionResult ViewTopic(string id, bool triedtolikeowntopic = false, int page = 1)
{
int realpage = page - 1;
int pageSize = 10;
if (triedtolikeowntopic)
ViewBag.Error = "You cannot like or dislike your own topic!";
var db = new ApplicationDbContext();
@ -329,8 +333,31 @@ public ActionResult ViewTopic(string id, bool triedtolikeowntopic = false)
return new HttpStatusCodeResult(404);
if (!ACL.CanSee(User.Identity.Name, topic.Parent))
return new HttpStatusCodeResult(403);
int pages = topic.Posts.GetPageCount(pageSize);
ViewBag.Page = realpage;
ViewBag.PageCount = pages;
ViewBag.PageSize = pageSize;
return View(topic);
}
}
public static class PaginationExtensions
{
public static int GetPageCount<T>(this IEnumerable<T> collection, int pageSize)
{
return (collection.Count() + pageSize - 1) / pageSize;
}
public static IEnumerable<T> GetItemsOnPage<T>(this IEnumerable<T> collection, int page, int pageSize)
{
var lst = collection.ToList();
for(int i = pageSize * page; i < pageSize + (pageSize * page) && i < lst.Count(); i++)
{
yield return lst[i];
}
}
}
}

View file

@ -1,4 +1,5 @@
@model Project_Unite.Models.ForumTopic
@using Project_Unite.Controllers;
@model Project_Unite.Models.ForumTopic
@using Microsoft.AspNet.Identity
@{
ViewBag.Title = Model.Subject;
@ -30,7 +31,7 @@
Html.RenderPartial("~/Views/Shared/_ModeratorBar.cshtml", Model);
}
@foreach (var post in Model.Posts.OrderBy(x => x.PostedAt))
@foreach (var post in Model.Posts.OrderBy(x => x.PostedAt).GetItemsOnPage(ViewBag.Page, ViewBag.PageSize))
{
if (Request.IsAuthenticated)
{
@ -75,3 +76,17 @@
@{
Html.RenderPartial("~/Views/Shared/_ModeratorBar.cshtml", Model);
}
<ul class="pagination">
@for(int i = 1; i <= ViewBag.PageCount; i++)
{
if (i == ViewBag.Page - 1)
{
<li class="active">@Html.ActionLink(i.ToString(), "ViewTopic", "Forum", null, new { id = Model.Discriminator, page = i })</li>
}
else
{
<li>@Html.ActionLink(i.ToString(), "ViewTopic", "Forum", null, new { id = Model.Discriminator, page = i })</li>
}
}
</ul>