在MVC中实现MongoDB的分页查询

来源:互联网 发布:浙工大图书馆网络 编辑:程序博客网 时间:2024/06/15 11:23

使用的MongoDB net 驱动是:MongoDB.Driver.2.4.4

首先确定的是MongoDB的BsonDocument结构:

var document = new BsonDocument {                            {"UserName",user.UserName },                            {"LoginIp",RequestHelper.GetIP() },                            {"Operation",new BsonDocument{{ "操作类型","登录" },{"操作员",user.RealName} } },                            {"CreateTime",DateTime.Now }                        };

其中,Operation 中的BsonDocument中的key,value键值对是可变长的,也就是说,不一定都是2个,根据需要,可能是2个,也可能是3个,4个等。

MVC的action实现:

 public ActionResult AdminLogList(string name = "", DateTime? start = null, DateTime? end = null, int pageindex = 1, int pagesize = 10)        {            ViewBag.name = name;            ViewBag.start = start;            ViewBag.end = end;            var collection = DBHelper.GetCollection("AdminLog");            var builder = Builders<BsonDocument>.Filter;            FilterDefinition<BsonDocument> filter = builder.Empty;            if (name.IsNotNullAndEmpty())            {                //filter = filter & builder.Eq("UserName", name);                //模糊查询                filter = filter & builder.Regex("UserName", new BsonRegularExpression("/.*" + name + ".*/"));            }            if (start.IsNotNullAndEmpty())            {                filter = filter & builder.Gte("CreateTime", start);            }            if (end.HasValue)            {                filter = filter & builder.Lte("CreateTime", end);            }            var sort = Builders<BsonDocument>.Sort.Descending("CreateTime");            var documents = collection.Find(filter).Sort(sort).ToList();            var query = documents.ToPagedList(pageindex, pagesize);            return View(query);        }

查询条件,一个name,可以进行模糊查询,一个开始日期,一个结束日期。按定义的BsonDocument 文档中的CreateTime键进行降序排列。

以下是cshtml中的相关代码,可能是都觉得cshtml中的实现代码很简单,因此我在网上搜索n遍,找不到相关实现代码。而对于我这样第一次实现 mongoDB 查询的人来说,根本不知道如何实现。所以我列出了我的实现。

头部部分:

@model  PagedList.IPagedList<MongoDB.Bson.BsonDocument>@using MongoDB.Bson;@using PagedList.Mvc;

查询部分:

<div class="list-header">        @using (Html.BeginForm(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["Controller"].ToString(), FormMethod.Post, new { @class = "form-inline", id = "search_form", role = "form", style = "" }))        {            @Html.AntiForgeryToken()            <!-- #region 职位筛选条件区域 start -->            <div class="col-xs-12 no-padding">                <div class="container-fluid">                    <!-- Collect the nav links, forms, and other content for toggling -->                    <ul class="nav navbar-nav">                        <li class="">                            <input type="text" class="form-control  input-sm" id="name" name="name" placeholder="操作员" value="@ViewBag.name">                                                       </li>                        <li>                            <div class=" input-group date form_datetime" data-date="@((ViewBag.start ?? DateTime.Now.AddMonths(-1)).ToShortDateString())">                                <input type="text" class="form-control  input-sm" id="start" name="start" style="width:100px;" placeholder="起始日期" value="@ViewBag.start"><span class="input-group-btn">                                    <button class="btn default date-reset btn-sm" type="button"><i class="fa fa-times"></i></button>                                    <button class="btn default date-set btn-sm" type="button"><i class="fa fa-calendar"></i></button>                                </span>                            </div>--                            <div class=" input-group date form_datetime" data-date="@((ViewBag.end ?? DateTime.Now.AddMonths(-1)).ToShortDateString())">                                <input type="text" class="form-control input-sm" id="end" name="end" style="width:100px;" placeholder="截止日期" value="@ViewBag.end">                                <span class="input-group-btn">                                    <button class="btn default date-reset btn-sm" type="button"><i class="fa fa-times"></i></button>                                    <button class="btn default date-set btn-sm" type="button"><i class="fa fa-calendar"></i></button>                                </span>                            </div>                        </li>                        <li>                            <div class="btn-group  navbar-right" role="group" aria-label="...">                                <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-search"></i><strong>筛选</strong></button>                            </div>                        </li>                    </ul>                </div><!-- /.container-fluid -->            </div>        }    </div>

列表及分页实现部分,这部分感觉最难,各种尝试,最终实现:

<div class=" list-item padding">        <table class="table table-bordered  table-striped">            <thead>                <tr>                                       <th>                        操作员                    </th>                    <th>                        登录ip                    </th>                    <th>                        操作                    </th>                                         <th>                        时间                    </th>                                     </tr>            </thead>            <tbody>                @foreach (var item in Model)                {                    <tr>                                               <td>                            @item["UserName"]                        </td>                        <td>                            @item["LoginIp"]                        </td>                        <td class="operation">                                                       @item["Operation"].ToJson()                        </td>                        <td>                            @item["CreateTime"].ToUniversalTime()                        </td>                                           </tr>                }            </tbody>        </table>        @Html.PagedListPager(Model, page => Url.Action(ViewContext.RouteData.Values["action"].ToString(), new { name = @ViewBag.name, start = @ViewBag.start, end = ViewBag.end, pageIndex = page }),                new PagedListRenderOptions                {                    LinkToFirstPageFormat = "<span class='glyphicon glyphicon-fast-backward'></span>",                    LinkToPreviousPageFormat = "<span class='glyphicon glyphicon-backward'></span>",                    LinkToNextPageFormat = "<span class='glyphicon glyphicon-forward'></span>",                    LinkToLastPageFormat = "<span class='glyphicon glyphicon-fast-forward'></span>",                    DisplayPageCountAndCurrentLocation = true,                    PageCountAndCurrentLocationFormat = "{0}/{1}页",                    DisplayItemSliceAndTotal = true,                    ItemSliceAndTotalFormat = "共{2}条记录"                })        <div class="action text-center">        </div>    </div>

操作部分json分解实现源码:

$(function () {                        $(".operation").each(function (index) {                var self = $(this);                //console.info($(this).text());                var obj = eval("(" + self.text() + ")");                var str = "";                $.each(obj, function (index, item) {                    str += index + ":" + item + "<br/>";                });                self.html(str);            });          });