Question

I am looking for the best way to implement a pager as per the following simple requirement.

I want a page like this

 <Pager 1 2 3 4 ...>

 <Partial View>

My action controller will look something like this...

    public PartialViewResult DisplayRecordDetails(int recordNumber)
    {
        MyRecord mr = GetRecord(recordNumber);
        return PartialView(mr);
    }

When I click on "1" (page index = 1), I pass 1 as a parameter to the DisplayRecordDetails action method and load the partial view with record 1.

When I click on "2" (page index = 2), I pass 2 as a parameter to the DisplayRecordDetails action method and load the partial view with record 2 and so on...

I will have the total item count info and current page index info at my disposal. Now how can I generate the pager dynamically with this info?

I have tried searching for pager libraries/helpers but all of them are for grids. How can I use them for my situation? I do not have a grid. I just have a partial view which I need to load dynamically depending on the page number.

Was it helpful?

Solution

You could design a view model which will contain all the id numbers:

public class MyViewModel
{
    // the currently selected id
    public int Id { get; set; }

    // a list of available ids
    public int[] Ids { get; set; }
}

And then have a controller action which will query your database or whatever and fetch the list of all available ids:

public ActionResult Index(int? id)
{
    var model = new MyViewModel
    {
        Id = id ?? 0,
        Ids = new[] { 563, 845, 845 } // those will come from your datasource
    };
    return View(model);
}

and in the corresponding view you could loop through those ids and generate links:

@model MyViewModel
<div>
    @Html.Action("DisplayRecordDetails", new { recordNumber = Model.Id })
</div>
@for (var i = 0; i < Model.Ids.Length; i++) 
{
    <span>@Html.ActionLink((i + 1).ToString(), "Index", new { id = i })</span>
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top