Home  >  Article  >  Backend Development  >  Asp.Net MVC code display for paging, retrieval, and sorting

Asp.Net MVC code display for paging, retrieval, and sorting

巴扎黑
巴扎黑Original
2017-08-16 16:14:421944browse

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 class="bottomline">管理用户</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 class="modal-title">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