EPiServer 7.5 and query strings

I recently worked on EPiServer 7.5 project where I had to create pagination for search results page.

Links for previous and next page look like this:

<a href="/search/?q=test">Previous</a>
<a href="/search/?q=test&p=3">Next</a>

I wanted to have search text and page number in the query string. If the page number is 1, then we don't want to have it in the query string.

Helper function:

public static MvcHtmlString PaginationLink(this HtmlHelper html, PageData currentPage,
                                            string query, int pageNumber)
{
    var queries = new NameValueCollection
    {
        { "q", query }
    };

    if (pageNumber != 1)
    {
        queries.Add("p", pageNumber.ToString());
    }

    var urlBuilder = new UrlBuilder(currentPage.LinkURL);
    urlBuilder.MergeQueryCollection(queries);

    Global.UrlRewriteProvider.ConvertToExternal(urlBuilder, null, Encoding.UTF8);

    return new MvcHtmlString(urlBuilder.ToString());
}

View:

@if (Model.SearchResult != null && Model.SearchResult.HasPreviousPage)
{
    <a href="@Html.PaginationLink(Model.CurrentPage,
                                    Model.SearchResult.SearchText,
                                    Model.SearchResult.PageNumber - 1)">Previous page</a>
}
@if (Model.SearchResult != null && Model.SearchResult.HasNextPage)
{
    <a href="@Html.PaginationLink(Model.CurrentPage,
                                    Model.SearchResult.SearchText,
                                    Model.SearchResult.PageNumber + 1)">Previous page</a>
}

SearchResult is a custom class in my view model that contains information about search text, number of hits returned, page size, etc.

comments powered by Disqus