Follow us

Header Ads

Paging in Asp.Net Core

Paging in Asp.Net Core

Packages

  • "Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" 
  • "Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"
  • "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" 

Controllers[Folder]

ProductsController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Paging.Helper;
using Searching.Data;
using Searching.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Searching.Controllers
{
    public class ProductsController : Controller
    {
        private readonly ApplicationDbContext _context;

        public ProductsController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index(int pageNumber = 1, string searchProductName = null)
        {
            var searchResult = _context.Products.AsNoTracking();
            if (!String.IsNullOrEmpty(searchProductName))
            {
                searchResult = _context.Products.Where(x => x.Title.Contains(searchProductName)).AsNoTracking();
                if (searchResult.Count() == 0)
                {
                    ViewBag.products = "Search Product Not Found";
                    return View();
                }
            }
            int pageSize = 5;
            return View(await PaginatedList<Product>.CreateAsync(searchResult, pageNumber, pageSize));
           }
        }
    }

Helper[Folder]

PaginatedList.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Paging.Helper
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }
        public PaginatedList(List<T> items,int count,int pageIndex,int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);
            this.AddRange(items);
        }
        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }
        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }
        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T>source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }

       
    }
}

Models[Folder]

ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;
using Searching.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Searching.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext>options):base(options)
        {

        }
        public DbSet<Product> Products { get; set; }
    }
}

Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Searching.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}

Views[Folder]

Products

Index.cshtml

@model Paging.Helper.PaginatedList<Product>

@{
    ViewData["Title"] = "Index";
}

<h1>Search</h1>
<form asp-action="Index">
    <div class="form-group">
        <label>Search Product Name:</label>
        <input type="text" name="searchProductName" class="form-control" />
        <input type="submit" vlaue="Search" />
    </div>
    @if(ViewBag.products!=null)
    {
    <span class="alert alert-danger">@ViewBag.products</span>
    }
<div>
    @if (Model != null)
    {
        <p>
            <a asp-action="Create">Create New</a>
        </p>
        <table class="table">
            <thead>
                <tr>
                    <th>
                        Title
                    </th>
                    <th>
                        Description
                    </th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Title)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Description)
                        </td>
                        <td>
                            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
        var nextDisabled = !Model.HasNextPage ? "disabled" : "";
        <a asp-action="Index"
           asp-route-sortOrder="@ViewData["CurrentSort"]"
           asp-route-pageNumber="@(Model.PageIndex - 1)"
           asp-route-currentFilter="@ViewData["CurrrentFilter"]"
           class="btn btn-primary @prevDisabled">
            Previous
        </a>
        <a asp-action="Index"
           asp-route-sortOrder="@ViewData["CurrentSort"]"
           asp-route-pageNumber="@(Model.PageIndex + 1)"
           asp-route-currentFilter="@ViewData["CurrrentFilter"]"
           class="btn btn-primary @nextDisabled">
            Next
        </a>
    }
</div>
</form>

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK1689\\MSSQL2019;Database=Search;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Searching.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Searching
{
    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.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Products}/{action=Index}/{id?}");
            });
        }
    }
}


Post a Comment

0 Comments