MVC paging with linq to sql and html helper class

To use paging in MVC you need to first create structure to pass values form page to HTML Helper class so first create a class to keep and pass the page information

public class PagingInfo
    public int TotalItems { get; set; }
    public int ItemsPerPage { get; set; }
    public int CurrentPage { get; set; }

    public int TotalPages
        get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }

It is just a convenient class for passing data between controller and the view, keep it separate from the domain model classes.

To keep helpers separate create a new folder HtmlHelpers

Create a new calss in this folder named PagingHelpers, we will create html helper method in this class with name PageLinks. Let's create the method

public static class PagingHelpers
        public static MvcHtmlString PageLinks(this HtmlHelper html, 
                         PagingInfo pagingInfo, Func<int, string> pageUrl)
            if(pagingInfo.TotalPages == 1)  
               return MvcHtmlString.Create(String.Empty);

            StringBuilder result = new StringBuilder();        
            for (Int index = 0; index < pagingInfo.TotalPages; index++)
                TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(index));                        
                tag.InnerHtml = (index + 1).ToString();
                if (i == pagingInfo.CurrentPage)
            return MvcHtmlString.Create(result.ToString());

The Func parameters provides the ability to pass in a delegate that will be used to generate the links to view other pages.

Remember that an extension method is available for use only when the namespace that contains it is in scope. There are two way to make it available 1. Add namespace with using 2. For Razor add @using statement to every view or add a configuration entry to the Web.config file, like this

        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />

Every namespace that we need to refer in a Razor view needs to be declared either in this way or in the view itself with an @using statement.

New create a view model

public class QuestionsListViewModel 
   public IEnumerable<Question> Questions{ get; set; }
   public PagingInfo PagingInfo { get; set; }

Now we need to update QuestionController class to use the QuestionsListViewModel class to provide the view with details of questions to display on the page and detail of the pagination, so let's do it

public ActionResult List(int page = 1)
   QuestionsListViewModel viewModel = new QuestionsListViewModel
       Questions = QuestionRepository.Questions
                                    .OrderBy(p => p.QuestionID)
                                    .Skip((page - 1) * PageSize)
       PagingInfo = new PagingInfo
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = QuestionRepository.Questions.Count()
   return View(viewModel);

That's we need to set now the time is to use our hard work and check the output, so do it and see the output:

<div class="pager">
       @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • linq to sql
By Ali Adravi On 03 Jan, 13  Viewed: 2,795

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 31,958

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 90,522

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 2,758

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 5,437

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 20,691