Bootstrap Pagination Dynamically In ASP.NET MVC

Introduction

This article will explain how to create bootstrap pagination dynamically in ASP.Net MVC. I will explain it with an example from an SQL database. Before understanding this article you should have a basic understanding of the following:

  • Bootstrap 4
  • MVC
  • Entity Framework
  • View Model
  • SQL Server

Step 1. Open your favorite SQL server database, any version. It doesn’t matter. Create the table's frontend and backend technology.

CREATE TABLE [dbo].[Blog](
    [Id] [int] IDENTITY(1,1) NOT NULL,
      NULL,
    [Url] [nvarchar](max) NULL,
    [Date] [datetime] NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY CLUSTERED
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Step 2. Now open Visual Studio 2017 or any version you wish.

ASP dot net web application

Step 3. Create an empty project in Visual Studio, and give it an appropriate name. Checked the MVC checkbox and clicked on OK.

Empty

Step 4. Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on the Models folder, select Add, then select New Item.

New item

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name MyModel (this name is not mandatory, you can give any name), and click "Add"

ADO dot net entity

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

Click on next

After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

Click on ok

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".

Click on next

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

Click on finish

Entity Framework gets added and the respective class gets generated under the Models folder.

Under the model folder

Step 5. Right-click on the Controllers folder to add a controller.

Controller

A window will appear. Choose MVC5 Controller-Empty and click "Add".

Bootstrap Pagination Dynamically In ASP.NET MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.

Home controller

Step 6. Right, click on the project “Add Folder” and name it ViewModel. Now right-click on this folder and “Add Class” with the name BlogViewModel.

using MvcBootstrapPaginationDynamic_Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MvcBootstrapPaginationDynamic_Demo.ViewModel
{
    public class BlogViewModel
    {
        public IEnumerable<Blog> Blogs { get; set; }
        public int BlogPerPage { get; set; }
        public int CurrentPage { get; set; }
        public int PageCount()
        {
            return Convert.ToInt32(Math.Ceiling(Blogs.Count() / (double)BlogPerPage));
        }
        public IEnumerable<Blog> PaginatedBlogs()
        {
            int start = (CurrentPage - 1) * BlogPerPage;
            return Blogs.OrderBy(b => b.Id).Skip(start).Take(BlogPerPage);
        }
    }
}

Controller Class Code

using MvcBootstrapPaginationDynamic_Demo.Models;
using MvcBootstrapPaginationDynamic_Demo.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcBootstrapPaginationDynamic_Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly MvcDemoContext db = new MvcDemoContext();
        public ActionResult Index(int page = 1)
        {
            var blogsView = new BlogViewModel
            {
                BlogPerPage = 5,
                Blogs = db.Blogs.OrderBy(d => d.Date),
                CurrentPage = page
            };
            return View(blogsView);
        }
    }
}

Step 7. Right-click on the Index action method in the controller class “Add View”

Click on Add view

Use a layout page

Index View Code

@model MvcBootstrapPaginationDynamic_Demo.ViewModel.BlogViewModel
@{
    ViewBag.Title = "Index";
}
<h3 class="text-uppercase">List of Blogs</h3>
@foreach (var blog in Model.PaginatedBlogs())
{
    <div class="alert alert-secondary rounded-0">
        <a href="@blog.Url" class="link" target="_blank">@blog.title</a>
        <span class="pull-right text-primary"><i class="fa fa-calendar"></i> @blog.Date.Value.ToString("dd-MM-yyyy")</span>
    </div>
}
<ul class="pagination">
    @for (int i = 1; i <= Model.PageCount(); i++)
    {
        <li class="@(i == Model.CurrentPage ? "page-item active" : "page-item")">
            <a class="page-link" href="@Url.Action("Index", new { page = i })">@i</a>
        </li>
    }
</ul>

Step 8. Install the latest version of Bootstrap and JQuery from the NuGet package manager under the tool in Visual Studio.

Step 9. Build your project and Run by pressing Ctrl+F5

List of blogs


Similar Articles