Last night I was working on a project that I've embarked upon as a learning exercise. I decided to add a pagination feature to my blog system. I made an attempt at it and got close... but I decided to undo my changes and I searched online for other 'better' solutions. I found this example which uses PagedList.Mvc NuGet and this example from asp.net which uses the same package.
Long story short, I decided that before I install another package I would make one more attempt at my own implementation and I was successful... so, on to my question.
Have I missed something important in my implementation that should make me want to reconsider my approach?
Here's my relevant Action in my HomeController.cs:
public ActionResult Index(int num = 0)
{
var postsPerPage = 3;
ViewBag.startNum = num;
using (UnitOfWork uwork = new UnitOfWork())
{
IEnumerable<Post> posts = uwork.PostRepository.GetAll().ToList();
int totalPosts = posts.Count();
ViewBag.pages = totalPosts / postsPerPage;
int skip = num * postsPerPage;
return View(posts.Skip(skip).Take(postsPerPage));
}
}
and this is the relevant code from my Index.cshtml:
<ul class="pagination">
<li>@Html.ActionLink("Home", "Index", "Home", new { num = 0 }, null)</li>
@for (var i = 1; i < ViewBag.pages + 1; i++)
{
var cur = i.ToString();
var name = i + 1;
<li>@Html.ActionLink(name.ToString(), "Index", "Home", new { num = cur }, null)</li>
if (i >= 10) { break; }
}
</ul>
Note: I know there's going to be a bit more logic required in order to account for the remainder of pages after they are divided. But that's not my biggest concern as of yet.