1. 程式人生 > 其它 >Csharp: ASP.NET Core 3.1 Razor Pages - Query and Pagination

Csharp: ASP.NET Core 3.1 Razor Pages - Query and Pagination

libman.json:

{
  "version": "1.0", //當前的libman檔案版本
  "defaultProvider": "cdnjs", //預設從哪個CDN網路下載檔案
  "libraries": [
    {
      "library": "[email protected]", //要下載的前端包名稱
      "destination": "wwwroot/lib/twitter-bootstrap/" //存放庫的檔案路徑地址
    },
    {
      "library": "[email protected]", //要下載的前端包名稱
      "destination": "wwwroot/lib/jquery/", //存放庫的檔案路徑地址
      "provider": "jsdelivr", //針對某個獨立的檔案,從其他源下載。
      "files": [ "dist/jquery.js", "dist/jquery.min.js" ] //下載該庫中特定的檔案,而不是下載所有的檔案

    },
    {
      "library": "[email protected]",
      "destination": "wwwroot/lib/jquery-validate"
    },
    {
      "library": "[email protected]",
      "destination": "wwwroot/lib/jquery-validate-unobtrusive"
    },
    {
      "provider": "jsdelivr",
      "library": "[email protected]",
      "destination": "wwwroot/lib/font-awesome"
    }
  ]
}

  

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace RazorPagesPagination
{
    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.AddSession();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //wwwroot 下的資料夾配置
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseMvc();
        }
    }
}

  

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ASP.NET Core Razor Pages - Pagination Example</title>
    <meta name="description" content=" geovindu,Geovin Du,塗聚文" />
    <meta name="keywords" content="geovindu,Geovin Du" />
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

    <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />


</head>
<body>
    <div class="container text-center">
        <div class="col">
            <h1>ASP.NET Core Razor Pages - Pagination Example</h1>
            @RenderBody()
        </div>
    </div>
    <hr />
    <div class="credits text-center">
        <p>
            <a href="http://jasonwatmore.com/post/2018/10/15/aspnet-core-razor-pages-pagination-example">ASP.NET Core Razor Pages - Pagination Example</a>
        </p>
        <p>
            <a href="http://jasonwatmore.com">JasonWatmore.com</a>
        </p>
    </div>


    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/twitter-bootstrap/js/bootstrap.min.js"></script>

    @RenderSection("Scripts", required: false)
</body>
</html>

  

Index.cshtml

@page
@model RazorPagesPagination.Pages.IndexModel
<!-- pager parameter controls -->
<form method="post" class="container border text-left pt-2 mb-3">
    <div class="form-row form-group">
        <div class="col">
            <label asp-for="TotalItems">Total number of items</label>
            <select asp-for="TotalItems" asp-items="Model.TotalItemsList" class="form-control form-control-sm" onchange="this.form.submit()"></select>
        </div>
        <div class="col">
            <label asp-for="PageSize">Items per page</label>
            <select asp-for="PageSize" asp-items="Model.PageSizeList" class="form-control form-control-sm" onchange="this.form.submit()"></select>
        </div>
        <div class="col">
            <label asp-for="MaxPages">Max page links displayed</label>
            <select asp-for="MaxPages" asp-items="Model.MaxPagesList" class="form-control form-control-sm" onchange="this.form.submit()"></select>
        </div>

        標題: <input type="text" asp-for="SearchKey" value="@Model.SearchKey" onchange="this.form.submit()" />
        <input type="submit" value="查詢" onchange="this.form.submit()" />
    </div>
</form>

<!-- items being paged -->
<table class="table table-sm table-striped table-bordered">
    @if (!Object.Equals(Model.DuItmes, null))
    {
        @foreach (var item in Model.DuItmes)
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.RealName</td>
                <td>@item.UserName</td>
            </tr>
        }
    }
    else
    {
        <tr>
            <td>No data!</td>
        </tr>

    }
</table>

<!-- pager -->
@if (!Object.Equals(Model.DuItmes, null))
{
    @if (Model.Pager.Pages.Any())
    {
        <nav class="table-responsive">
            <ul class="pagination justify-content-center d-flex flex-wrap">
                @if (Model.Pager.CurrentPage > 1)
                {
                    <li class="page-item">
                        <a class="page-link" href="/">First</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="/?p=@(Model.Pager.CurrentPage - 1)">Previous</a>
                    </li>
                }

                @foreach (var p in Model.Pager.Pages)
                {
                    <li class="page-item @(p == Model.Pager.CurrentPage ? "active" : "")">
                        <a class="page-link" href="/?p=@p">@p</a>
                    </li>
                }

                @if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
                {
                    <li class="page-item">
                        <a class="page-link" href="/?p=@(Model.Pager.CurrentPage + 1)">Next</a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="/?p=@(Model.Pager.TotalPages)">Last</a>
                    </li>
                }
            </ul>
        </nav>
    }
}

  

Index.cshtml.cs

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using JW; //JW.Pager

//https://github.com/cornflourblue/JW.Pager
//

namespace RazorPagesPagination.Pages
{

    /// <summary>
    /// geovindu,Geovin Du,塗聚文
    /// </summary>
    public class IndexModel : PageModel
    {
        public IEnumerable<string> Items { get; set; }

        public List<Person> DuItmes { get; set; }

        public List<Person> dummyItems { get; set; }
        public Pager Pager { get; set; }
        public SelectList TotalItemsList { get; set; }
        public int TotalItems { get; set; }
        public SelectList PageSizeList { get; set; }
        public int PageSize { get; set; }
        public SelectList MaxPagesList { get; set; }
        public int MaxPages { get; set; }

        [BindProperty(SupportsGet = true)]
        public string SearchKey { get; set; }

        public void OnGet(int p = 1)
        {
            // properties for pager parameter controls
            TotalItemsList = new SelectList(new []{ 10, 150, 500, 1000, 5000, 10000, 50000, 100000, 1000000 });
            TotalItems = HttpContext.Session.GetInt32("TotalItems") ?? 150;
            PageSizeList = new SelectList(new []{ 1, 5, 10, 20, 50, 100, 200, 500, 1000 });
            PageSize = HttpContext.Session.GetInt32("PageSize") ?? 10;
            MaxPagesList = new SelectList(new []{ 1, 5, 10, 20, 50, 100, 200, 500 });
            MaxPages = HttpContext.Session.GetInt32("MaxPages") ?? 10;
            SearchKey = HttpContext.Session.GetString("SearchKey" ?? "");
            // generate list of sample items to be paged

            //查詢一遍是空值
            var dummyItems = Person.GetAllPerson().AsQueryable();// var dummyItems =Enumerable.Range(1, TotalItems).Select(x => "Item " + x);
            if(object.Equals(dummyItems,null))
            {
               var dummyItemdd = Person.GetAllPerson();
                dummyItems = dummyItemdd.AsQueryable();
            }
            if (!string.IsNullOrEmpty(SearchKey))
            {
                dummyItems = dummyItems.Where(b => b.RealName.Contains(SearchKey)|| b.UserName.Contains(SearchKey));
                if (dummyItems.Count() > 0)
                {
                    Pager = new Pager(dummyItems.Count(), p, PageSize, MaxPages);

                    // assign the current page of items to the Items property  DuItmes
                    //Items = dummyItems.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize);
                    DuItmes = dummyItems.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize).ToList();
                }
            }
            else
            {
                // get pagination info for the current page
                Pager = new Pager(dummyItems.Count(), p, PageSize, MaxPages);

                // assign the current page of items to the Items property
                //Items = dummyItems.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize);
                DuItmes = dummyItems.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize).ToList();
            }
        }

        public IActionResult OnPost(int totalItems, int pageSize, int maxPages)
        {
            // update pager parameters for session and redirect back to 'OnGet'
            HttpContext.Session.SetInt32("TotalItems", totalItems);
            HttpContext.Session.SetInt32("PageSize", pageSize);
            HttpContext.Session.SetInt32("MaxPages", maxPages);
            HttpContext.Session.SetString("SearchKey", SearchKey);
            return Redirect("/");
        }
    }


    public class Person
    {
        /// <summary>
        /// 
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string RealName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string UserName { get; set; }


        public static List<Person> GetAllPerson()
        {
            List<Person> listPerson = new List<Person>
            {
                new Person{Id=1,RealName="塗聚文",UserName="geovindu1" },
                new Person{Id=2,RealName="塗聚文",UserName="geovindu2" },
                new Person{Id=3,RealName="塗聚文",UserName="geovindu3" },
                new Person{Id=4,RealName="塗聚文",UserName="geovindu4" },
                new Person{Id=5,RealName="塗聚文",UserName="geovindu5" },
                new Person{Id=6,RealName="塗聚文",UserName="geovindu6" },
                new Person{Id=7,RealName="塗聚文",UserName="geovindu7" },
                new Person{Id=8,RealName="塗聚文",UserName="geovindu8" },
                new Person{Id=9,RealName="塗聚文",UserName="geovindu9" },
                new Person{Id=10,RealName="塗聚文",UserName="geovindu10" },
                new Person{Id=11,RealName="塗聚文",UserName="geovindu11" },
                new Person{Id=12,RealName="塗聚文",UserName="geovindu12" },
                new Person{Id=13,RealName="塗聚文",UserName="geovindu13" },
                new Person{Id=14,RealName="塗聚文",UserName="geovindu14" },
                new Person{Id=15,RealName="塗聚文",UserName="geovindu15" },
                new Person{Id=16,RealName="塗聚文",UserName="geovindu16" },
                new Person{Id=17,RealName="塗聚文",UserName="geovindu17" },
                new Person{Id=18,RealName="塗聚文",UserName="geovindu18" },
                new Person{Id=19,RealName="塗聚文",UserName="geovindu19" },
                new Person{Id=20,RealName="塗聚文",UserName="geovindu20" },
                new Person{Id=21,RealName="塗聚文",UserName="geovindu21" },
                new Person{Id=22,RealName="塗聚文",UserName="geovindu22" },
                new Person{Id=23,RealName="塗聚文",UserName="geovindu23" },
                new Person{Id=24,RealName="塗聚文",UserName="geovindu24" },
                new Person{Id=25,RealName="塗聚文",UserName="geovindu25" },
                new Person{Id=26,RealName="塗聚文",UserName="geovindu26" },
                new Person{Id=27,RealName="塗聚文",UserName="geovindu27" },
                new Person{Id=28,RealName="塗聚文",UserName="geovindu28" },
                new Person{Id=29,RealName="塗聚文",UserName="geovindu29" },
                new Person{Id=30,RealName="塗聚文",UserName="geovindu30" },
            };

            return listPerson;
        }
    }
}