search
HomeBackend DevelopmentC#.Net TutorialAsp.Net MVC code display for paging, retrieval, and sorting

Many times we need such a function to paginate, sort and retrieve tables. This article mainly introduces the overall implementation of Asp.Net MVC paging, retrieval, and sorting. Those who are interested can learn more.

Many times we need such a function to paginate, sort and retrieve tables. There are many ways to implement this, including ready-made table controls, front-end mvvm, and user controls. But many times when you look at something very beautiful and want to further control it, it is not so satisfactory. I'll implement it here by myself. The functions are not comprehensive, but I hope it's clear and understandable. Garden friends are also welcome to contribute. The front-end is bootstrap3+jPaginate, and the back-end is based on membership. Nothing difficult.

First, the renderings.

#Paging is actually to handle the number of items per page, the total number of items, the total number of pages, and the current page. In order to facilitate reuse, let’s start with the warehouse.

1. Establish a warehouse

1. Define the Ipager interface. The model warehouse that needs paging inherits this interface


namespace Protal.Model.Abstract
{
  /// <summary>
  /// 分页处理
  /// </summary>
  public interface IPager
  {
    /// <summary>
    /// 每页项目数
    /// </summary>
    /// <value>The page item count.</value>
   int PageItemCount { get; set; }
   /// <summary>
   /// 总页数
   /// </summary>
   /// <value>The totoal page.</value>
    int TotoalPage { get; }
    /// <summary>
    /// 显示的页数
    /// </summary>
    /// <value>The display page.</value>
    int DisplayPage { get; set; }
    /// <summary>
    /// 满足条件的总数目
    /// </summary>
    int TotalItem { get; set; }
  }
}

2. Define IUsersRepository, which mainly handles User-related business logic. The Find function is the main query method, and order means forward and reverse sorting.


 public interface IUsersRepository : IPager
  {
    /// <summary>
    /// Post list
    /// </summary>
    /// <param name="order">Order expression</param>
    /// <param name="filter">Filter expression</param>
    /// <param name="skip">Records to skip</param>
    /// <param name="take">Records to take</param>
    /// <returns>List of users</returns>
    IEnumerable<User> Find(int order=0,string filter="", int skip = 0, int take = 10);
    /// <summary>
    /// Get single post
    /// </summary>
    /// <param name="name">User id</param>
    /// <returns>User object</returns>
    User FindByName(string name);
    /// <summary>
    /// Add new user
    /// </summary>
    /// <param name="user">Blog user</param>
    /// <returns>Saved user</returns>
    User Add(User user);
    /// <summary>
    /// Update user
    /// </summary>
    /// <param name="user">User to update</param>
    /// <returns>True on success</returns>
    bool Update(User user);
    /// <summary>
    /// Save user profile
    /// </summary>
    /// <param name="user">Blog user</param>
    /// <returns>True on success</returns>
    bool SaveProfile(User user);
    /// <summary>
    /// Delete user
    /// </summary>
    /// <param name="userName">User ID</param>
    /// <returns>True on success</returns>
    bool Remove(string userName);
  }

2. Warehouse implementation and binding

Main method: User in Membership It is different from what we customized, so there is a conversion


 public class UsersRepository : IUsersRepository
  {
    /// <summary>
    /// The _user list
    /// </summary>
    private List<User> _userList = new List<User>();
    /// <summary>
    /// The _page item count
    /// </summary>
    private int _pageItemCount;
    /// <summary>
    /// The _display page
    /// </summary>
    private int _displayPage;
    /// <summary>
    /// The _usercount
    /// </summary>
    private int _usercount;
    /// <summary>
    /// The _total item
    /// </summary>
    private int _totalItem;
    /// <summary>
    /// 标记是否有查询条件 没有的话则返回全部数目
    /// </summary>
    private Func<User, bool> _func;

    /// <summary>
    /// Gets or sets the users.
    /// </summary>
    /// <value>The users.</value>
    public List<User> Users
    {
      get
      {
        int count;
        var usercollection = Membership.GetAllUsers(0, 999, out count);
        if (count == _usercount) return _userList;
        _usercount = count;
        var members = usercollection.Cast<MembershipUser>().ToList();
        foreach (var membershipUser in members)//这里存在一个转换
        {
          _userList.Add(new User
          {
            Email = membershipUser.Email,
            UserName = membershipUser.UserName,
            //roles password
          });
        }
        return _userList;
      }
      set { _userList = value; }
    }   
//查询
public IEnumerable<User> Find(int order = 0, string filter = "", int skip = 0, int take = 10)
    {
      if (take == 0) take = Users.Count;
      //过滤
      _func = string.IsNullOrEmpty(filter) ? (Func<User, bool>) (n => n.UserName != "") : (n => n.UserName.Contains(filter));
      var users = Users.Where(_func).ToList();
      //更新总数目
      _totalItem = users.Count;
      users = order == 0 ? users.OrderBy(n => n.UserName).ToList() : users.OrderByDescending(n => n.UserName).ToList();
      return users.Skip(skip).Take(take);
    }
 /// <summary>
    /// 每页项目数
    /// </summary>
    /// <value>The page item count.</value>
    public int PageItemCount
    {
      get
      {
        if (_pageItemCount == 0)
        {
          _pageItemCount = ProtalConfig.UserPageItemCount;
        }
        return _pageItemCount;
      }
      set { _pageItemCount = value; }
    }

    /// <summary>
    /// 总页数
    /// </summary>
    /// <value>The totoal page.</value>
    public int TotoalPage
    {
      get
      {
        var page = (int) Math.Ceiling((double) TotalItem/PageItemCount);
        return page==0?1:page; 
      }
    }
    /// <summary>
    /// 显示的页数
    /// </summary>
    /// <value>The display page.</value>
    public int DisplayPage
    {
      get
      {
        if (_displayPage == 0)
        {
          _displayPage = ProtalConfig.UserDisplayPage;
        }
        return _displayPage;
      }
      set { _displayPage = value; }
    }


    /// <summary>
    /// 满足条件的总数目 保持更新
    /// </summary>
    /// <value>The total item.</value>
    public int TotalItem
    {
      get
      {
        if (_func == null)
          _totalItem = Users.Count;
        return _totalItem;
      }
      set { _totalItem = value; }
    }
}

ProtalConfig.UserDisplayPage. Here, a default number of pages is implemented through configuration, so that users can change the rows and columns in webconfig. number.


public static int UserPageItemCount
        {
          get
          {
            if (_userPageItemCount == 0)
            {
              _userPageItemCount = WebConfigurationManager.AppSettings["UserPageItemCount"] != null ?
                Convert.ToInt16(WebConfigurationManager.AppSettings["UserPageItemCount"]) : 5;
            }
            return _userPageItemCount;
          }
          set
          {
            _userPageItemCount = value;
          }
        }

Then bind:


 _kernel.Bind<IUsersRepository>().To<UsersRepository>();

3. Controller part

We need two pages, a main page Index, and a partial view UserTable responsible for partial refresh

The following are the main methods, the main logic is processed in the warehouse .


  [Authorize]
  public class UserManagerController : Controller
  {
    /// <summary>
    /// The _repository
    /// </summary>
    private readonly IUsersRepository _repository;

    /// <summary>
    /// Initializes a new instance of the <see cref="UserManagerController"/> class.
    /// </summary>
    /// <param name="iRepository">The i repository.</param>
    public UserManagerController(IUsersRepository iRepository)
    {
      _repository = iRepository; 
    }

    /// <summary>
    /// Indexes the specified page index.
    /// </summary>
    /// <param name="pageIndex">Index of the page.</param>
    /// <returns>ActionResult.</returns>
    public ActionResult Index(int pageIndex=1)
    {
      ViewBag.DisplayPage = _repository.DisplayPage;
      pageIndex = HandlePageindex(pageIndex);
     
      //支持地址栏直接分页
      ViewBag.CurrentPage = pageIndex;
      return View();
    }


    /// <summary>
    /// Users table. 分页模块
    /// </summary>
    /// <param name="pageIndex">Index of the page.</param>
    /// <param name="order">The order.</param>
    /// <param name="filter">The filter str.</param>
    /// <returns>ActionResult.</returns>
    public ActionResult UserTable(int pageIndex = 1, int order = 0, string filter = "")
    {
      pageIndex = HandlePageindex(pageIndex);
      var skip = (pageIndex - 1) * _repository.PageItemCount;
      var users = _repository.Find(order,filter, skip, _repository.PageItemCount);
      
      //总用户数
      ViewBag.TotalUser = _repository.TotalItem;
      //总页数
      ViewBag.TotalPageCount = _repository.TotoalPage; ;

      return PartialView(users);
    }

    /// <summary>
    /// 处理页数 防止过大或过小
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    private int HandlePageindex(int index)
    {
      var totoalpage = _repository.TotoalPage;
      if (index == 0) return 1;
      return index > totoalpage ? totoalpage : index;
    }
}

4. View part Html jquery

1.Index.cshtml


<script src="~/Scripts/form.js"></script>
<p class="container">
  <h4 id="管理用户">管理用户</h4>
  <p>
    <button data-target="#adduser" id="adduserbt" data-toggle="modal" class="btn btn-info btn-hover">新增用户</button>
    <button class="btn btn-danger" id="deluser">删除</button>
    <span class="errorinfo"></span>
    <input type="search" class="pull-right" id="usersearch" placeholder="搜索"/>
  </p>
  <p id="userpart">
     @Html.Action("UserTable",new{pageIndex=ViewBag.CurrentPage})
  </p>
  <p id="userpager"></p>
  <input type="hidden" id="dispalypage" value="@ViewBag.DisplayPage"/>
  <input type="hidden" id="page" value="@ViewBag.CurrentPage"/>
  <input type="hidden" id="currentpage" value="@ViewBag.CurrentPage"/>

</p>
<p class="modal fade adduserbox"id="adduser" tabindex="1" role="dialog" aria-hidden="true">
  <p class="modal-content">
    <p class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true" >×</button>
       <h4 id="Add-nbsp-new-nbsp-User">Add new User</h4>
    </p>
    <p class="modal-body">
      @{
        Html.RenderAction("Create","UserManager");
      }
    </p>
  </p>
</p>

@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
}

2.UserTable.cshtml, the role part has not been processed yet. After this table is updated, the number of users who meet the conditions and the new total number of pages will also be updated, triggering Jpaginate to re-paginate.


@model IEnumerable<Protal.Model.Data.User.User>
 <table id="usertable" class="table table-striped table-condensed table-hover table-bordered">
    <tr>
      <th><input type="checkbox" id="allcheck" /><label for="allcheck">全选</label></th>
      <th><a href="#" id="usersort" data-order="0" class="glyphicon-sort">名称</a></th>
      <th>角色</th>
      <th>E-mail</th>
    </tr>
    <tbody>
      @foreach (var item in Model) {
        <tr>
          <td> <input type="checkbox" data-id="@item.UserName" /></td>
          <td> <a>@item.UserName</a> </td>
          <td> @Html.Raw(item.Role) </td>
          <td> @item.Email</td>
        </tr>
      }</tbody>
   <tfoot>
     <tr>
       <td colspan="4">
         <span>@Html.Raw("共"+ViewBag.TotalUser+"人")</span> @*<span>@ViewBag.TotalPageCount</span>*@
       </td>
     </tr>
   </tfoot>
  </table>
 <input type="hidden" id="totoalpage" value="@ViewBag.TotalPageCount"/>

3. Script

The ones used like checkall and infoShow are some simple methods that have been extended by themselves for selecting all and prompting.


$(function () {

    var options = {
      dataType: &#39;json&#39;,
      success: processJson
    };
    pageagin($("#totoalpage").val());
    //分页
    function pageagin(totalcount) {
      $("#userpager").paginate({
        count: totalcount,
        start: $("#page").val(),
        dispaly: $("#dispalypage").val(),
        boder: false,
        border_color: &#39;#fff&#39;,//自己调整样式。
        text_color: &#39;black&#39;,
        background_color: &#39;none&#39;,
        border_hover_color: &#39;#ccc&#39;,
        text_hover_color: &#39;#000&#39;,
        background_hover_color: &#39;#fff&#39;,
        images: false,
        mouse: &#39;press&#39;,
        onChange: function (page) { //翻页
          paging(page);
          $("#currentpage").val(page);
        }
      });
    }
    //分页更新
    function paging(page) {
      $.post("/Users/UserTable", { pageIndex: page, order: $("#userpart").attr("data-order"), filter: $.trim($("#usersearch").val()) }, function (data) {
        $("#userpart").html(data);
      });
    }

    //排序
    $("#usersort").live("click",function () {
      $("#userpart").triggerdataOrder();
      paging( $("#currentpage").val());
    });
    
    //搜索
    $("#usersearch").keyup(function() {
      paging($("#currentpage").val());
      pageagin($("#totoalpage").val());
    });

    //处理form
    $("#userForm").submit(function () {
      $(this).ajaxSubmit(options);
      return false;
    });
    function processJson(data) {
      if (data == 1) {
        location.reload();
      } else {
        alert("添加失败");
      }
    }

    //高亮
    $("#unav li:eq(0)").addClass("active");
    $("#adnav li:eq(2)").addClass("active");
    //全选/全不选
    $("#allcheck").checkall($("#usertable tbody input[type=&#39;checkbox&#39;]"));

    //删除用户
    $("#deluser").click(function () {
      var checks = $("#usertable tbody input[type=&#39;checkbox&#39;]:checked");
      var lens = checks.length;
      if (lens == 0) {
        $.infoShow("未选择删除对象",0);
        return false;
      }
      if (confirm("确定要删除所选中用户?")) {
        for (var i = 0; i < lens; i++) {
          var $chek = checks.eq(i);
          var id = $chek.attr("data-id");
          var tr = $chek.parent().parent();
          $.post("Users/DeleteUser", { id: id }, function (data) {
            if (data == 1) {
              tr.fadeOut();
              $.infoShow("删除成功", 1);
            } else {
              $.infoShow("删除失败", 0);
            }
          });
        }
      }
       return true;
    });
    
    // 增加用户
    $("#adduserbt").click(function() {
      $(".modal-header").show();
    });
  })

Here are all the codes for your reference.

Let me show you two more renderings, one is the grid of kendoui, and the other is the paging done by Angular. I will introduce it to you later when I have the opportunity.

Kendo- Grid

Kendo is highly integrated with the MVC framework. Its core code is as follows:


@model IEnumerable<Kendo.Mvc.Examples.Models.ProductViewModel>

@(Html.Kendo().Grid(Model)
  .Name("Grid")
  .Columns(columns =>
  {
    columns.Bound(p => p.ProductID).Groupable(false);
    columns.Bound(p => p.ProductName);
    columns.Bound(p => p.UnitPrice);
    columns.Bound(p => p.UnitsInStock);
  })
  .Pageable()
  .Sortable()
  .Scrollable() 
  .Filterable()  
  .DataSource(dataSource => dataSource    
    .Ajax()
    .ServerOperation(false)    
   )
)

The core of AngularJs still calls the encapsulated API function, which is equivalent to the method in the warehouse above, and then binds it through the model.

To summarize: the amount of code implemented by myself is relatively large, the functions are incomplete, and it feels like reinventing the wheel, but it can be better controlled and is basically enough; the kendo method feels like Gao Daquan, the development speed is fast when you are familiar with it. Just have more references, and you need to worry about conflicts between Kendoui and other UI frameworks. I don't know enough about the front-end MVVM method. I feel that the amount of code in the front-end script is quite large, and the effect is good. But the generated html code is very little. The table above. Chrome F12 or right-click to view the source code, it will look like this:

The main thing is just a p


 <p data-ng-app="blogAdmin" data-ng-view="" id="ng-view"></p>

Self-protection is pretty good, too There may be a problem with SEO. There should be a better way, please give me some pointers.




  Name of the blog (Admin)
  
  
  
  
  
  
  
  






  


  
  
  

<p data-ng-app="blogAdmin" data-ng-view="" id="ng-view"></p>

PS: This thing is not difficult. The logic is all in the warehouse. For those who want the source code, I will separate it and post it later. Of course, there are many ways to do this, and I am not trying to show off any framework, but the needs of my current project are so separated. One controller is available to solve all problems, but my other models also need to be paginated and easy to test. Should I write them all in the controller?

The above is the detailed content of Asp.Net MVC code display for paging, retrieval, and sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
使用Python实现XML数据的筛选和排序使用Python实现XML数据的筛选和排序Aug 07, 2023 pm 04:17 PM

使用Python实现XML数据的筛选和排序引言:XML是一种常用的数据交换格式,它以标签和属性的形式存储数据。在处理XML数据时,我们经常需要对数据进行筛选和排序。Python提供了许多有用的工具和库来处理XML数据,本文将介绍如何使用Python实现XML数据的筛选和排序。读取XML文件在开始之前,我们需要先读取XML文件。Python有许多XML处理库,

C++程序:按字母顺序重新排列单词的位置C++程序:按字母顺序重新排列单词的位置Sep 01, 2023 pm 11:37 PM

在这个问题中,一个字符串被作为输入,我们必须按字典顺序对字符串中出现的单词进行排序。为此,我们为字符串中的每个单词(之间用空格区分)分配一个从1开始的索引,并以排序索引的形式获得输出。String={“Hello”,“World”}“Hello”=1“World”=2由于输入字符串中的单词已按字典顺序排列,因此输出将打印为“12”。让我们看看一些输入/结果场景-假设输入字符串中的所有单词都相同,让我们看看结果-Input:{“hello”,“hello”,“hello”}Result:3获得的结

如何优化Java集合排序性能如何优化Java集合排序性能Jun 30, 2023 am 10:43 AM

Java是一种功能强大的编程语言,广泛应用于各类软件开发中。在Java开发中,经常会涉及到对集合进行排序的场景。然而,如果不对集合排序进行性能优化,可能会导致程序的执行效率下降。本文将探讨如何优化Java集合排序的性能。一、选择合适的集合类在Java中,有多种集合类可以用来进行排序,如ArrayList、LinkedList、TreeSet等。不同的集合类在

Java开发中如何优化集合排序去重性能Java开发中如何优化集合排序去重性能Jul 02, 2023 am 11:25 AM

Java开发中,集合排序和去重是常见的需求。然而,在处理大数据集合时,性能往往会成为一个问题。本文将介绍一些优化技巧,帮助提升集合排序和去重的性能。一、使用合适的数据结构在Java中,最常用的数据结构是ArrayList和HashSet。ArrayList适用于需要保持元素顺序的情况,而HashSet则适用于需要去重的情况。在排序和去重的场景中,我们可以使用

如何利用vue和Element-plus实现数据的分组和排序如何利用vue和Element-plus实现数据的分组和排序Jul 18, 2023 am 10:39 AM

如何利用Vue和ElementPlus实现数据的分组和排序Vue是一种流行的JavaScript框架,它可以帮助我们构建前端应用程序。ElementPlus是基于Vue的桌面端组件库,它提供了丰富的UI组件,使我们能够轻松地构建出漂亮且用户友好的界面。在本文中,我们将探讨如何利用Vue和ElementPlus来实现数据的分组和排序。首先,我们需要准备一

PHP usort() 函数使用指南:排序数组PHP usort() 函数使用指南:排序数组Jun 27, 2023 pm 02:27 PM

PHPusort()函数使用指南:排序数组在PHP编程中,我们经常需要对数组进行排序。PHP提供了很多函数用于数组的排序,其中usort()函数可以灵活的对数组进行自定义排序。本文将介绍usort()函数的使用方法和注意事项,并通过实例演示如何使用usort()函数对数组进行排序。一、usort()函数简介PHPusort()函数

Java实现的常见排序算法详解Java实现的常见排序算法详解Jun 18, 2023 am 10:48 AM

排序算法是计算机科学中的一个重要概念,是许多应用程序的核心部分。在日常生活和工作中,我们经常需要对数据进行排序,例如排列名单、对数值进行排序等。Java作为一种广泛使用的编程语言,提供了许多内置的排序算法。本文将详细介绍Java中实现的常见排序算法。1.冒泡排序(BubbleSort)冒泡排序是最简单但最慢的排序算法之一。它遍历整个数组,比较相邻的元素并一

如何在Java 14中使用Records类来实现自动比较和排序如何在Java 14中使用Records类来实现自动比较和排序Jul 30, 2023 pm 01:06 PM

如何在Java14中使用Records类来实现自动比较和排序Java14引入了一种新的类称为Records类,它为我们提供了一种简洁而强大的方式来定义不可变的数据类。Records类具有自动为每个字段生成getter方法、equals()方法和hashCode()方法的特性,这使得比较和排序非常方便。在这篇文章中,我们将通过示例代码来演示如何在Java

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.