网盘操作日志

写在前面

上篇文章介绍了一个bootstrap的分页插件,这篇将弄一个完整的例子,就以日志分页为例说明如何请求服务端然后进行分页。

实现

前端通过ajax的方式请求Controller中的action获取json数据,前端收到数据后动态的绑定到table上面。BaseRepository泛型类中实现分页的方法。

/// <summary>
/// 分页查询
/// </summary>
/// <typeparam name="SEntity"></typeparam>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecord"></param>
/// <param name="where"></param>
/// <param name="isAsc"></param>
/// <param name="orderLambda"></param>
/// <returns></returns>
public IQueryable<TEntity> FindPaged<S>(int pageIndex, int pageSize, out int totalRecord, Expression<Func<TEntity, bool>> where, bool isAsc, Expression<Func<TEntity, S>> orderLambda)
{

    var _list = netDiskContext.Set<TEntity>().Where<TEntity>(where);
    totalRecord = 0;
    if (_list != null)
    {
        totalRecord = _list.Count<TEntity>();
        if (isAsc)
        {
            _list = _list.OrderBy<TEntity, S>(orderLambda).Skip<TEntity>((pageIndex - 1) * pageSize).Take<TEntity>(pageSize);
        }
        else
        {
            _list = _list.OrderByDescending<TEntity, S>(orderLambda).Skip<TEntity>((pageIndex - 1) * pageSize).Take<TEntity>(pageSize);
        }
    }
    return _list;
}

在LogController中的GetLogs方法使用该方法,如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Wolfy.NetDisk.BLL;
using Wolfy.NetDisk.IBLL;
using Wolfy.NetDisk.Model;
using Wolfy.NetDisk.Site.Models;

namespace Wolfy.NetDisk.Site.Controllers
{
    public class LogController : Controller
    {
        private ILogServiceRepository _logServiceRepository = new LogServiceRepository();
        //
        // GET: /Log/
        public ActionResult Index()
        {
            UserInfo user = Session["user"] as UserInfo;
            if (user == null)
            {
                return RedirectToAction("Login", "UserInfo");
            }
            return View();
        }
        [HttpGet]
        public JsonResult GetLogs()
        {
            int totalRecord = 0;

            int page = Convert.ToInt32(Request.Params["page"]);
            UserInfo userInfo = Session["user"] as UserInfo;
            int pageSize = 10;
            page = page <= 0 ? 1 : page;
            int totalPage = Convert.ToInt32(Math.Ceiling(totalRecord * 1.0 / pageSize));

            var myLogs = _logServiceRepository.FindPaged<DateTime>(page, pageSize, out totalRecord, x => string.IsNullOrEmpty(x.Exception) && x.user.Id == userInfo.Id, false, x => x.Dt).ToList();

            if (myLogs == null)
            {
                return new JsonResult() { Data = new JavaScriptSerializer().Serialize(new { _code = 500 }), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
            List<LogViewModel> lstLogs = new List<LogViewModel>();
            foreach (var item in myLogs)
            {
                lstLogs.Add(new LogViewModel()
                {
                    Id = item.Id,
                    Dt = item.Dt,
                    Opt = item.Operation
                });
            }
            return new JsonResult() { Data = new JavaScriptSerializer().Serialize(new { _data = lstLogs, _code = 200, total = totalPage }), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}

前端调用,默认加载第一页数据,设置分页插件的配置,如下所示:

@model IEnumerable<Wolfy.NetDisk.Model.Log>

@{
    ViewBag.Title = "操作日志";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
    //将json格式的时间转换成一般时间
    function ChangeDateFormat(jsondate) {
        jsondate = jsondate.replace("/Date(", "").replace(")/", "");
        if (jsondate.indexOf("+") > 0) {
            jsondate = jsondate.substring(0, jsondate.indexOf("+"));
        } else if (jsondate.indexOf("-") > 0) {
            jsondate = jsondate.substring(0, jsondate.indexOf("-"));
        }
        var date = new Date(parseInt(jsondate, 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        var minitue = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        var secends = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + minitue + ":" + secends;
    }
    $(function () {
        var element = $('#logPage');
        var options = {
            size: "large",
            bootstrapMajorVersion: 3,
            //当前页
            currentPage: 1,
            //可以改变显示的页码数
            numberOfPages: 5,
            //总页数
            totalPages: 11
        };
        function requestServer(pageIndex) {
            $.getJSON('/Log/GetLogs?page=' + pageIndex, function (data) {
                console.log(data);
                data = JSON.parse(data);
                options.totalPages = data.totalPage;
                $('#dvLog').html('');
                $('<table class="table table-bordered table-hover table-striped table-top" id="tbLog"><tr><th>序号</th> <th>操作日志</th><th>操作时间</th> </tr></table>').appendTo($('#dvLog'));;
                for (var i = 0; i < data._data.length; i++) {
                    var current = data._data[i];
                    $('<tr><td data-id=' + current.Id + '>' + (i + 1) + '</td><td>' + current.Opt + '</td><td>' + ChangeDateFormat(current.Dt) + '</td></tr>').appendTo($('#tbLog'));
                };

            });
        };
        function loadData(pageIndex) {

            options.onPageClicked = function (e, originalEvent, type, page) {
                //页码单击事件
                console.log(page);
                options.currentPage = page;

                requestServer(page);

            };
            requestServer(pageIndex);
            element.bootstrapPaginator(options);

        };

        loadData(1);
    });
</script>

<div class="tableContent" style="width:95%;" id="dvLog">

</div>
<div class="bjui-pageContent tableContent" style="width:95%;position:relative;">
    <ul id='logPage' class="bjui-pageFooter" style="margin:0 auto; margin-left:30%;"></ul>
</div>

结果

总结

使用起来还是比较简单的。分页样式也不错。