One of the most important feature on a website that has a search feature is that it allows for pagination (allow you to page the results). The reason you would want to make pages is to make your website run faster for the user. Rather than displaying 1000 results on one page you can change it to display 10 results on one each page with a total of 100 pages, which speeds up the site and makes navigation easier.

You will need to install the nuget package PagedList.Mvc. This will automatically install the package PagedList as well.

In my example I am working with a search feature, where the user will enter a string in the textbox and the Index controller will query the Documents  database for a matching Title.

In the controller we will need to pass another parameter int page, which is the number of pages and assign it to 1 as a default value. Then in the linq query we need to add ToPagedList(page, 10). The page  being the number of pages, and 10 is the number of results per page.

Search Controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
[HttpPost]
public ActionResult Index(string q, int page = 1)
 {
    try
    {
       if (ModelState.IsValid)
       {
          string queryString = q;
          IQueryable<Document> result = Enumerable.Empty<Document>().AsQueryable()
          var db = new NotesModel();
          var res = (from m in db.Documents
                     where m.Title.Contains(q)
                     select m).OrderByDescending(m => m.Title).ToPagedList(page, 10);
          return View(res);
        }
     }
     catch (Exception ex)
     {
         ViewBag.Error = ex.Message;
     }
     return View();
 }

In the view rather than using @model IEnumerable<Document> you would use @model IPagedList<Document>, because in the linq query we convert it to ToPagedList.

View:

1
2
3
4
5
6
7
8
@model IPagedList<Document>
 
<div id="searchResult">
    <div class="pagedList>
         @Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
    </div>
</div>
//Render results here