Adding Simple Pagination To Search Results View Using Linq in Umbraco

Adding pagination can be a pain - especially if you're otherwise happy with your code and don't look forward to re-writing it now that a need for pagination has arisen! Fortunately, there is a simple way you can do this on any type of collection using Linq that we find very helpful! Best of all it's totally flexible: while you could easily include this logic directly in your search result view, you can just as easily structure some of this functionality into the controller or library. This example assumes you have a model that includes a list of results stored in the 'Results' property of the model

    var Page = 1;
    var ResultsPerPage = 10;
    var totalResults = model.Results.Count();
    var TotalPages = (int)Math.Ceiling((double)totalResults / (double)ResultsPerPage);

    if (!string.IsNullOrEmpty(Request.QueryString["page"]))
        int.TryParse(Request.QueryString["page"], out Page);
        if (Page < 1) { Page = 1; }

        if (Page > totalPages) { Page = totalPages; }  

        // ... (then some way down your view where you display the results) ... 
        @foreach (var singleItem in model.Results.Skip((Page - 1) * ResultsPerPage)
                        .Take(ResultsPerPage)) { 

                // display single item here 

This gives you the basic idea, it may be helpful to create (for example) a helper method to render a single item, then within the foreach(...) loop you can simply pass it the current item, but otherwise this gives you a neat way to add pagination to existing code without the need to rewrite it!

Need an Umbraco Master?

Here at Simon Antony, we have an in house certified Umbraco Grand Master available for hire. Got a problem with your site, need architecture advice, give us a call to speak to Simon directly and see how we can help

Contact Simon Today!