Tuesday, 6 December 2022

Paging (Pagination) example in ASP.Net Core MVC

 In this article I will explain with an example, how to implement Paging (Pagination) in ASP.Net Core MVC.

Paging (Pagination) will be implemented using Entity Framework in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Note: The Customers Table of the Northwind Database will be used in this project.
 
 
Downloading Entity Framework Core
You will need to install the Microsoft.EntityFrameworkCore.SqlServer package using the following command.
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.1.1
 
 
Model
Once the package is successfully installed, create a Folder named Models in your project and then a new class by right clicking the Models folder and then click on Add and then New Item option of the Context Menu. 
Then create the following properties inside the Model class.
The following Model class named CustomerModel consists of three properties.
1. Customers – List collection of the Customer Class which will hold the records of the Customers Table.
Note: In this article, only four Columns will be displayed and hence four properties are added to the class.
 
2. CurrentPageIndex – Holds the value of the index of the Current Page.
3. PageCount – This value is calculated using the Maximum Rows to be displayed and the Total Records present in the Table.
public class CustomerModel
{
    ///<summary>
    /// Gets or sets Customers.
    ///</summary>
    public List<Customer> Customers { get; set; }
 
    ///<summary>
    /// Gets or sets CurrentPageIndex.
    ///</summary>
    public int CurrentPageIndex { get; set; }
 
    ///<summary>
    /// Gets or sets PageCount.
    ///</summary>
    public int PageCount { get; set; }
}
 
public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}
 
 
Database Context
1. Now you will need to add a new class to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
Paging (Pagination) example in ASP.Net Core MVC
 
2. Inside the class, first inherit the EntityFrameworkCore namespace and then inherit the DbContext class.
Then using Dependency Injection, a Constructor is created DbContextOptions are passed as parameter and also the Constructor of base class i.e. DbContext class is inherited.
Finally, a DbSet Collection property of Customer Model class is created, which will be later used for holding the Data fetched from SQL Server Database Table.
using Paging_EF_Core_MVC.Models;
using Microsoft.EntityFrameworkCore;
namespace Paging_EF_Core_MVC
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<Customer> Customers { get; set; }
    }
}
 
 
Adding the Connection String inside AppSettings.json
The following Connection String setting has been added in the AppSettings.json file.
{
 "ConnectionStrings": {
    "MyConn": "Data Source=.\\SQL2017;Initial Catalog=Northwind;Integrated security=true"
 }
}
 
 
Configuring Database Context in Startup class
Inside the Startup class, the IConfiguration is injected in the Startup class and assigned to the private property Configuration.
Then the Connection String is read from the AppSettings.json file and is used to add the DbContext service.
Note: For more details on reading Connection String inside the Startup class, please refer my article .Net Core: Read Connection String inside Startup.cs from AppSettings.json file.
 
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
namespace Paging_EF_Core_MVC
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            string conStr = this.Configuration.GetConnectionString("MyConn");
            services.AddDbContext<DBCtx>(options => options.UseSqlServer(conStr));
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
 
 
Controller
There are two Action methods with the name Index, one for handling the GET operation while other for handing the POST operation.
GetCustomers method
The GetCustomers method accepts currentPage parameter. It has a fixed variable named maxRows which determines the maximum records to be displayed per page.
Note: You can change the value of the maxRows variable as per your requirement and also fetch its value from AppSettings so that you don’t have to modify the code every time.
 
First an object of the CustomerModel class is created and then the records are fetched from the Customers table using Entity Framework and are set to the Customers property of the CustomerModel object.
The PageCount value is calculated by dividing the count of the records by the maximum rows to be displayed.
The currentPage parameter value is assigned to the CurrentPageIndex property.
The Paging is performed on the records using the Skip and Take functions.
The Skip function accepts the Start Index from the set of records to fetched i.e. if Page Index is 1 then the Start Index will be ( 1 - 1) * 10 = 0.
Example: If Current Page Index is 1 and the Maximum Rows is 10 then the Start Index will be (1 - 1) * 10 = 0
 
The Take function will fetch the rows based on the value of the maxRows variable.
GET operation
Inside the GET Action method, the GetCustomers method is called with the currentPage parameter value passed as 1 as when the View is accessed for the first time the records of the first page will be displayed.
POST operation
Inside the post Action method, the value of the CurrentPageIndex is passed to the GetCustomers method.
public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public IActionResult Index()
    {
        return View(this.GetCustomers(1));
    }
    [HttpPost]
    public IActionResult Index(int currentPageIndex)
    {
        return View(this.GetCustomers(currentPageIndex));
    }
 
    private CustomerModel GetCustomers(int currentPage)
    {
        int maxRows = 10;
        CustomerModel customerModel = new CustomerModel();
 
        customerModel.Customers = (from customer in this.Context.Customers
                                    select customer)
                    .OrderBy(customer => customer.CustomerID)
                    .Skip((currentPage - 1) * maxRows)
                    .Take(maxRows).ToList();
 
        double pageCount = (double)((decimal)this.Context.Customers.Count() / Convert.ToDecimal(maxRows));
        customerModel.PageCount = (int)Math.Ceiling(pageCount);
 
        customerModel.CurrentPageIndex = currentPage;
 
        return customerModel;
    }
}
 
 
View
Inside the View, in the very first line the CustomerModel is declared as Model for the View.
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
For displaying the records, an HTML Table is used. A loop will be executed over the Customers property of the CustomerModel class which will generate the HTML Table rows with the Customer records.
For building the Pager, a FOR loop is executed from value 1 to the value of the PageCount property for generating an HTML Table for Pager.
When a HTML Anchor inside the Pager is clicked a JavaScript function named PagerClick is executed which sets the Index of the clicked Pager button into a HiddenField and then submits the form.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using Paging_EF_Core_MVC.Models;
@model CustomerModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <h4>Customers</h4>
    <hr/>
    <form asp-action="Index" asp-controller="Home" method="post">
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th>CustomerID</th>
                <th>ContactName</th>
                <th>City</th>
                <th>Country</th>
            </tr>
            @foreach (Customer customer in Model.Customers)
            {
                <tr>
                    <td>@customer.CustomerID</td>
                    <td>@customer.ContactName</td>
                    <td>@customer.City</td>
                    <td>@customer.Country</td>
                </tr>
            }
        </table>
        <br/>
        <table cellpadding="0" cellspacing="0">
            <tr>
                @for (int i = 1; i <= Model.PageCount; i++)
                {
                    <td>
                        @if (i != Model.CurrentPageIndex)
                        {
                            <a href="javascript:PagerClick(@i);">@i</a>
                        }
                        else
                        {
                            <span>@i</span>
                        }
                    </td>
                }
            </tr>
        </table>
        <input type="hidden" id="hfCurrentPageIndex" name="currentPageIndex"/>
    </form>
    <script type="text/javascript">
            function PagerClick(index) {
                document.getElementById("hfCurrentPageIndex").value = index;
                document.forms[0].submit();
            }
    </script>
</body>
</html>
 
 
Screenshot
Paging (Pagination) example in ASP.Net Core MVC

Get selected (checked) CheckBox Row values of HTML Table using jQuery

 In this article I will explain with an example, how to get selected (checked) CheckBox Row (Cell) values of HTML Table using jQuery.

When the Button is clicked, all the CheckBoxes inside the HTML Table will be referenced and then the Row (Cell) values of selected (checked) CheckBoxes will be extracted and displayed using JavaScript Alert Message Box.
 
 
HTML Markup
The following HTML Markup consists of an HTML Table and a Button.
<table cellspacing="0" rules="all" border="1" id="Table1" style="border-collapse: collapse;">
    <tr>
        <th>&nbsp;</th>
        <th style="width:80px">Customer Id</th>
        <th style="width:120px">Name</th>
        <th style="width:120px">Country</th>
    </tr>
    <tr>
        <td><input type="checkbox"/></td>
        <td>1</td>
        <td>John Hammond</td>
        <td>United States</td>
    </tr>
    <tr>
        <td><input type="checkbox"/></td>
        <td>2</td>
        <td>Mudassar Khan</td>
        <td>India</td>
    </tr>
    <tr>
        <td><input type="checkbox"/></td>
        <td>3</td>
        <td>Suzanne Mathews</td>
        <td>France</td>
    </tr>
    <tr>
        <td><input type="checkbox"/></td>
        <td>4</td>
        <td>Robert Schidner</td>
        <td>Russia</td>
    </tr>
</table>
<br />
<input id = "btnGet" type="button" value="Get Selected" />
 
 
Get selected (checked) CheckBox Row values of HTML Table using jQuery
Inside the jQuery document ready event handler, the Button has been assigned a jQuery Click event handler.
When the Button is clicked, a jQuery each loop is executed over all the selected (checked) CheckBoxes inside the HTML Table and the values of Cells of the Row are extracted and displayed using JavaScript Alert Message Box.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        //Assign Click event to Button.
        $("#btnGet").click(function () {
            var message = "Id Name                  Country\n";
 
            //Loop through all checked CheckBoxes in GridView.
            $("#Table1 input[type=checkbox]:checked").each(function () {
                var row = $(this).closest("tr")[0];
                message += row.cells[1].innerHTML;
                message += "   " + row.cells[2].innerHTML;
                message += "   " + row.cells[3].innerHTML;
                message += "\n";
            });
 
            //Display selected Row data in Alert Box.
            alert(message);
            return false;
        });
    });
</script>
 
 
Screenshot
Get selected (checked) CheckBox Row values of HTML Table using jQuery
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

Implementing paging in ASP.NET Core MVC

 This post is about how to implement paging in ASP.NET Core MVC applications. For the implementation I am using a nuget package - X.PagedList.Mvc.Core. In the controller action method we need to set the page as the argument like this.

public IActionResult Index(int? page = 1)
{
    if (page != null && page < 1)
    {
        page = 1;
    }

    var pageSize = 10;

    var shortLinks = _tinyLinksDatabaseContext.ShortLinks
        .OrderByDescending(s => s.CreatedAt)
        .ToPagedList(page ?? 1, pageSize);

    return View(shortLinks);
}

And in the Index view, we can configure the table and pager component. I am using Razor For loop and HTML table to build the table grid structure.

@model IPagedList<ShortLink>
@{
    ViewData["Title"] = "Home Page";
}

@if (Model != null && Model.Count > 1)
{
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th scope="col">Url</th>
                    <th scope="col">ShortUrl</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var shortLink in Model)
                {
                    <tr>
                        <td scope="col">@shortLink.Url</td>
                        <td scope="col">@shortLink.ShortUrl</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

And implement the Pager component like this. Since I am using Bootstrap library, I am using Bootstrap pager styles.

<nav>
@Html.PagedListPager(Model, page => Url.Action("index", new { page = page }), new PagedListRenderOptions()
{
    ActiveLiElementClass = "active",
    PageClasses = new[]{ "page-link"},
    LiElementClasses=new[] { "page-item" },
    UlElementClasses = new[] { "pagination","justify-content-center", "mt-3" },
    LinkToNextPageFormat = "Next",
    LinkToPreviousPageFormat = "Previous",
    MaximumPageNumbersToDisplay = 5,
    DisplayLinkToPreviousPage = PagedListDisplayMode.Always,
    DisplayLinkToNextPage = PagedListDisplayMode.Always
})
</nav>

The advantage of this approach is we don’t need to implement the paging logic in SQL code. We can see the Entity Framework core logs and we will be able to see the SQL query with paging parameters, like this.

EF Core logging with paging logic

And the data will be displayed like this with Bootstrap table and pager.

Table with Paging logic

Paging will help you to improve the application performance by loading the data partially.

Saturday, 3 December 2022

A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)

 Original answer:

You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string (also not recommended):


TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.


Changed in appsettings.json file:

{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "ConnectionStrings": {

    "DefaultConnection": "Server=WKWIN9498383; Database=dbGridCustom;TrustServerCertificate=True; Trusted_Connection=True; MultipleActiveResultSets=true"

  },

  "AllowedHosts": "*"

}