Step by step create ASP.NET MVC5 program [Repository+Autofac+Automapper+SqlSugar] (11)

Keywords: ASP.NET Programming

Preface

Little buddies,
Hello, everyone. I'm Rector.
Rector has been busy changing jobs recently and has not had much time to update our ASP.NET MVC 5 series articles. [Step by step create ASP.NET MVC5 program Repository+Autofac+Automapper+SqlSugar] Until now, I have just squeezed some time to update an article. My friends have been waiting too long.

Writing a series of articles is not an easy thing, I believe that friends who have written a series of articles should also have some experience.

Points of knowledge in this paper

This issue is the eleventh in the series, and the last in the series. Step by step create ASP.NET MVC5 program [Repository+Autofac+Automapper+SqlSugar] (10) We learned about master pages and partial views, and reorganized the HTML code of the common area of the page using master pages and partial views. In this article, we will cover:

  • Universal Paging Encapsulation
  • Implementation of Paging Articles

Universal Paging Encapsulation

In the previous two issues, our article list page did not have paging function, but used the following methods:

public IEnumerable<Post> FindHomePagePosts(int limit = 20)
        {
            using (var db = DbFactory.GetSqlSugarClient())
            {
                var list = db.Queryable<Post>().OrderBy(x => x.Id, OrderByType.Desc).Take(limit).ToList();
                return list;
            }
        }

To read the first N(20) records in the article table as the data source of the article list on the home page. Then, this paper will encapsulate a general paging information class and paging generic method, and finally realize the data paging function of the home page article list. Paging effect is as follows:

Creation and Implementation of IPagedList Interface

Open the project TsBlog.Repositories and create two new classes in this project: IPagedList.cs and PagedList.cs. The code is as follows:

IPagedList.cs

using System.Collections.Generic;

namespace TsBlog.Repositories
{
    public interface IPagedList<T> : IList<T>
    {
        int PageIndex { get; }
        int PageSize { get; }
        int TotalCount { get; }
        int TotalPages { get; }
        bool HasPreviousPage { get; }
        bool HasNextPage { get; }
    }
}

IPagedLIst.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace TsBlog.Repositories
{
    /// <summary>
    /// Paging Component Entity Class
    /// </summary>
    /// <typeparam name="T">generic entity </typeparam>

    [Serializable]
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        /// <summary>
        ///Constructor
        /// </summary>
        /// <param name="source">data source </param>
        /// <param name="page index">paging index </param>
        /// <param name="pageSize">paging size </param>
        public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var total = source.Count();
            TotalCount = total;
            TotalPages = total / pageSize;

            if (total % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;

            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
        }

        /// <summary>
        ///Constructor
        /// </summary>
        /// <param name="source">data source </param>
        /// <param name="page index">paging index </param>
        /// <param name="pageSize">paging size </param>
        public PagedList(IList<T> source, int pageIndex, int pageSize)
        {
            TotalCount = source.Count();
            TotalPages = TotalCount / pageSize;

            if (TotalCount % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
        }

        /// <summary>
        ///Constructor
        /// </summary>
        /// <param name="source">data source </param>
        /// <param name="page index">paging index </param>
        /// <param name="pageSize">paging size </param>
        ///<param name="total Count">total number of records </param>
        public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
        {
            TotalCount = totalCount;
            TotalPages = TotalCount / pageSize;

            if (TotalCount % pageSize > 0)
                TotalPages++;

            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source);
        }

        /// <summary>
        /// Paging Index
        /// </summary>
        public int PageIndex { get; }
        /// <summary>
        /// Paging Size
        /// </summary>
        public int PageSize { get; private set; }
        /// <summary>
        /// Total Records
        /// </summary>
        public int TotalCount { get; }
        /// <summary>
        //Total page number
        /// </summary>
        public int TotalPages { get; }

        /// <summary>
        /// Is there a previous page?
        /// </summary>
        public bool HasPreviousPage
        {
            get { return (PageIndex > 0); }
        }
        /// <summary>
        /// Is there the next page?
        /// </summary>
        public bool HasNextPage
        {
            get { return (PageIndex + 1 < TotalPages); }
        }
    }
}

Among them, IPagedList.cs is a paging information interface, which contains the basic information of paging, such as: Page Index, Page Size, Total Count, Total Pages and so on. The PagedList.cs class file is the implementation of IPagedList.cs interface.

Add generic storage paging interface

Open the IRepository.cs file of the project TsBlog.Repositories and create a new paging interface in it, as follows:

/// <summary>
/// Query paging data according to conditions
/// </summary>
/// <param name="predicate"></param>
/// <param name="orderBy"></param>
/// <param name= "page index">current page index </param>
/// <param name="pageSize">distribution size </param>
/// <returns></returns>
IPagedList<T> FindPagedList(Expression<Func<T, bool>> predicate, string orderBy = "", int pageIndex = 1, int pageSize = 20);

Open the GenericRepository.cs generic warehouse implementation class in this project and implement FindPagedList as a paging method, as follows:

/// <summary>
/// Query paging data according to conditions
/// </summary>
/// <param name="predicate"></param>
/// <param name="orderBy"></param>
/// <param name= "page index">current page index </param>
/// <param name="pageSize">distribution size </param>
/// <returns></returns>
public IPagedList<T> FindPagedList(Expression<Func<T, bool>> predicate, string orderBy = "", int pageIndex = 1, int pageSize = 20)
{
    using (var db = DbFactory.GetSqlSugarClient())
    {
        var totalCount = 0;
        var page = db.Queryable<T>().OrderBy(orderBy).ToPageList(pageIndex, pageSize, ref totalCount);
        var list = new PagedList<T>(page, pageIndex, pageSize, totalCount);
        return list;
    }
}

Similarly, open the project TsBlog.Services, open the file IService.cs, and add the paging service interface as follows:

/// <summary>
/// Query paging data according to conditions
/// </summary>
/// <param name="predicate"></param>
/// <param name="orderBy"></param>
/// <param name= "page index">current page index </param>
/// <param name="pageSize">distribution size </param>
/// <returns></returns>
IPagedList<T> FindPagedList(Expression<Func<T, bool>> predicate, string orderBy = "", int pageIndex = 1, int pageSize = 20);

Open the generic service class GenericService.cs in this project and implement the paging service interface as follows:

/// <summary>
/// Query paging data according to conditions
/// </summary>
/// <param name="predicate"></param>
/// <param name="orderBy"></param>
/// <param name= "page index">current page index </param>
/// <param name="pageSize">distribution size </param>
/// <returns></returns>
public IPagedList<T> FindPagedList(Expression<Func<T, bool>> predicate, string orderBy = "", int pageIndex = 1, int pageSize = 20)
{
    return _repository.FindPagedList(predicate, orderBy, pageIndex, pageSize);
}

At this point, the general paging interface and implementation of our generic warehouse and service are encapsulated. Now we need to use the above paging encapsulation to realize the paging function of the article list in the UI layer.

Switch to project TsBlog.Frontend.

Installing third-party paging components

For convenience, this example tutorial uses a third-party paging component to realize the paging function of UI layer: PagedList. Installation method is: nuget, so similar to previous installations of nuget package, open the nuget package management tool, search the keyword PagedList, in the query package, select PagedList.Mvc and PagedList two paging component packages and install, as follows:

After the paging component is installed, we open the HomeController controller and modify the Index Action. The modified HomerController.cs code is as follows:

using PagedList;
using System.Linq;
using System.Web.Mvc;
using TsBlog.AutoMapperConfig;
using TsBlog.Frontend.Extensions;
using TsBlog.Services;
using TsBlog.ViewModel.Post;

namespace TsBlog.Frontend.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// Article Service Interface
        /// </summary>
        private readonly IPostService _postService;
        public HomeController(IPostService postService)
        {
            _postService = postService;
        }
        /// <summary>
        //Home page
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int? page)
        {
            //var list = _postService.FindHomePagePosts();
            //Read paging data and return IPagedList < Post >
            page = page ?? 0;
            var list = _postService.FindPagedList(x => !x.IsDeleted && x.AllowShow, pageIndex: (int)page, pageSize: 10);
            var model = list.Select(x => x.ToModel().FormatPostViewModel());
            ViewBag.Pagination = new StaticPagedList<PostViewModel>(model, list.PageIndex, list.PageSize, list.TotalCount);
            return View(model);
        }
    }
}

Finally, open the view file corresponding to Index: / Views/Home/Index.cshtml, add paging control, as follows:

@using PagedList
@using PagedList.Mvc
@model IEnumerable<TsBlog.ViewModel.Post.PostViewModel>
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "ASP.NET MVC 5 Series of article tutorials--home page";
}
<div class="jumbotron">
    <h1>Hello, buddy</h1>
    <p>Welcome to Rector Of ASP.NET MVC 5 A series of article tutorials. Ad locum, Rector Create an integration step by step with you Repository+Autofac+Automapper+SqlSugar Of WEB Applications.</p>
    <p>Are you ready?</p>
    <p>......</p>
    <p>Let's get started. ASP.NET MVC 5 Explore the application!!!</p>
</div>
<strong class="post-title">Article list(@(Model.Count())piece)</strong>
<ul class="list-unstyled post-item-box">
    @foreach (var p in Model)
    {
        <li>
            <h2><a href="~/post/details/@p.Id">@p.Title</a></h2>
            <p class="post-item-summary">@p.Summary ... <a href="~/post/details/@p.Id">Read the whole passage</a></p>
        </li>
    }
</ul>
@Html.PagedListPager((IPagedList)ViewBag.Pagination, page => Url.Action("index", new { page }), new PagedListRenderOptions
{
    LinkToFirstPageFormat = "home page",
    LinkToPreviousPageFormat = "Previous page",
    LinkToNextPageFormat = "next page",
    LinkToLastPageFormat = "Last",
    DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
    DisplayLinkToLastPage = PagedListDisplayMode.Never,
    DisplayEllipsesWhenNotShowingAllPageNumbers = true,
    MaximumPageNumbersToDisplay = 5
})

After all the above changes have been completed, we have completed the encapsulation and implementation of universal paging. Of course, this universal paging is very simple and can only meet the paging query and reading of single form data. More complex paging requirements should be implemented according to your own ideas.

After completing the above steps, we recompiled and generated the project TsBlog.Frontend. Finally, open the address in the browser: http://localhost:54739/ Check if the data paging function works.

Well, if you like Rector or this series of articles, please give me a compliment to encourage Rectro to continue to write better articles or series of articles.

Source Hosting Address for this issue: Please go to the initial address of \\\\\\\ Step by step create ASP.NET MVC5 program [Repository+Autofac+Automapper+SqlSugar] (11) View

If you are not addicted to the tutorial, you are welcome to join the official QQ group of Tuheng. 483350228. If you have problems in running the program restored according to the tutorial, please refer to the source code corresponding adjustment and modification in this issue. You are also welcome to join the QQ group. What do you know? C

Thank you for your patience. This series is not finished yet. See you next time.

At the same time, we also welcome you to pay attention to our. NET programming enthusiast community: https://2sharings.com Every day. NET development technology dry goods update oh.

[https://2sharings.com ] A. NET programming enthusiast community, focusing on. NET/C# development, helps you find more elegant and advanced solutions to difficult problems

Posted by Dark57 on Wed, 02 Jan 2019 09:03:09 -0800