layui+asp.net webapi实现分页模糊查询

小伙伴们早上好呀,现在姐姐讲解的是如何用layui+asp.net webapi实现分页模糊查询。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200607093600461.png#pic_center)

图[1.0]分页模糊查询示意图

  <div class="layui-card">
                    <!-- 搜索框-->
                    <div class="layui-card-header">
                        <div class="layui-row">
                            <div class="layui-col-md4">.</div>
                            <div class="layui-col-md4">
                                <div class="layui-card-header">
                                    <input id="content" type="text" placeholder="搜索标题" class="search-input" />
                                    <a class="a-search" onclick="searchData();"><i class="iconfont" style="font-size:35px;">&#xe654;</i></a>
                                </div>
                            </div>
                            <div class="layui-col-md4">.</div>
                        </div>
                    </div>
                    <div class="layui-card-body">
                        <div>
                            <div class="layui-row">
                                <div class="layui-col-md2">.</div>
                                <div class="layui-col-md8">
                                    <!-- 显示:法律数据、分页、模糊查询 -->
                                    <!-- 数据初始化bigin -->
                                    <!-- 分页 -->
                                    <div id="paging" style="margin:0 0px 0 180px;"></div>
                                    <!-- 加载数据的地方 -->
                                    <div class="law-dataItem">
                                        <ul class="ul-law-dataItem"></ul>
                                    </div>
                                </div>
                                <div class="layui-col-md2">.</div>
                            </div>
                        </div>
                    </div>
                </div>
  <style>
        .a-shishi {
            font-family: 'microsoft yahei','Helvetica Neue', Helvetica, Arial, sans-serif;
            /*上右下左*/
            padding: 0 12px 0 12px;
            font-size: 18px;
            line-height: 39px;
        }

        .a-search {
            color: #969696 !important;
            position: absolute;
            width: 30px;
            height: 30px !important;
            margin: 0 0 0 -45px;
            cursor: pointer;
        }

        .search-input {
            border-radius: 40px;
            height: 30px;
            font-size: 14px;
            background: #eee;
            border: 1px solid #eee;
            padding: 0 40px 0 20px;
            width: 150px;
        }
    </style>
<script>
    //初始化分页
    $(function () {
        var id = $.getUrlParam('id');//法律类型编号

        getPageData(id, $().msgBoardCountByFuzzy(id, ""));
    });

    //获得“url”传递过来的参数
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //获得分页总数
    $.fn.msgBoardCountByFuzzy = function getCount(lTId, lTitle) {
        var userNumber;
        var pa_SpecificTemplate = {
            LTId: lTId,             //法律类型编号
            LTitle: lTitle          //具体法律的标题
        }
        $.ajax({
            url: "/api/Law/getCountByLike",
            type: "POST",
            data: JSON.stringify(pa_SpecificTemplate),
            async: false,
            dataType: "json",
            contentType: "application/json",
            success: function (index) {
                userNumber = index;
            }
        });
        return userNumber;
    };//getCount end

    //分页显示法律
    function ShowDataByFuzzy(pageSize, currPage, lTId, lTitle) {
        var law = {
            PageSize: pageSize,  //每页所显示的条数
            PageNo: currPage,    //当前页
            LTId: lTId,          //法律类型编号
            LTitle: lTitle       //具体法律标题
        };
        $.ajax({
            url: "/api/Law/getPageDataByFlow",
            type: "POST",
            async: false,//AJAX设置为异步
            data: JSON.stringify(law),
            dataType: "json",
            contentType: "application/json",
            success: function (data) {
                $(data).each(function (index, item) {
                    var data = '<li style="border-bottom: 1px solid #f0f0f0; margin: 0 0 15px; padding: 15px 2px 20px 0; position: relative; word-wrap: break-word;>';
                    data += '<a style="position:absolute;top:50%;margin-top:-60px;right:0;width:125px;height:100px;">';
                    data += '</a>';
                    data += '<div>';
                    //标题
                    data += '<a href="../ChildrenTwo_desk/law-basic-children.html?LTId=' + $.getUrlParam('id') + "&LId=" + item.LId + '" style="cursor:pointer;color:#333;margin:-7px 0 4px;display:inherit;font-size:18px;font-weight:700;line-height:1.5;">' + item.LTitle + '</a>';
                    //文本内容【做了限定】
                    if (item.LContentText.length > 400) {
                        data += '<p style="margin:0 0 8px;font-size:13px;line-height:24px;color:#999;display: block;width:880px;">' + item.LContentText.substr(0, 400) + "......" + '</p>';
                    } else
                        data += '<p style="margin:0 0 8px;font-size:13px;line-height:24px;color:#999;display: block;width:880px;">' + item.LContentText + '</p>';
                    data += '</div>';
                    data += '</div>';
                    data += '</li>';

                    $(".ul-law-dataItem").append(data);
                });//each end
            }
        });//ajax end
    }//ShowData

    //法律类型编号、法律具体数据的总数
    function getPageData(TId, total, lTitle) {
        layui.use(['laypage', 'layer'], function () {
            var laypage = layui.laypage, layer = layui.layer;
            var currPage = 1;
            laypage.render({
                elem: 'paging',//指向存放分页的容器,值可以是容器ID、DOM对象
                count: total,//数据总数。一般通过服务端得到
                curr: currPage,//当前页数
                limit: 10,//每页显示的条数
                prev: "<<",//上一页图标
                next: ">>",//下一页图标
                theme: "#0099ff",//分页主色
                layout: ['count', 'prev', 'page', 'next', 'skip'],//设置分页组件显示
                jump: function (obj, first) {
                    currPage = obj.curr;//当前页数
                    $(".ul-law-dataItem").empty();
                    ShowDataByFuzzy(10, currPage, TId, lTitle);//当前页、每页显示的条数、法律类型编号
                }
            });
        });
    }//function end

    //模糊查询
    function searchData() {
        var id = $.getUrlParam('id');//法律类型编号
        var dataBylike = $("#content").val();
        var getCountByPage = getPageData(id, $().msgBoardCountByFuzzy(id, dataBylike));//得到分页加模糊查询后的总数
        getPageData(id, getCountByPage, dataBylike);
    }//function end
</script>
在这里插入代码片
/// <summary>
        /// 显示分页(包括模糊查询的操作)
        /// </summary>
        /// <param name="law"></param>
        /// <returns></returns>
        [HttpPost]
        public List<Model.nf_Law> getPageDataByFlow([FromBody]Page.pa_nf_Law law)
        {
            return new BLL.BLL_nf_Law().getPageDataByFlow(law);
        }

        /// <summary>
        /// 获得分页的总数(包括模糊查询分页的操作)
        /// </summary>
        /// <param name="law"></param>
        /// <returns></returns>
        [HttpPost]
        public int getCountByLike([FromBody]Page.pa_nf_Law law)
        {
            return new BLL.BLL_nf_Law().getCountByLike(law);
        }
  /// <summary>
        /// 分页
        /// 说明:自带“模糊查询”
        /// </summary>
        /// <param name="law"></param>
        /// <returns></returns>
        public List<Model.nf_Law> getPageDataByFlow(Page.pa_nf_Law law)
        {
            Dictionary<string, object> condition = null;

            //如果有模糊查询的业务,则如下
            if (!string.IsNullOrEmpty(law.LTitle))
            {
                condition = getDataLike(new Model.nf_Law() { LTitle=law.LTitle });
                return new DAL.DAL_nf_Law().getPageDataByFlow(condition,law);
            }

            //如果没有模糊查询的业务,就直接返回“-1”(是一个标记,如果有模糊查询的业务就返回那个集合)
            return new DAL.DAL_nf_Law().getPageDataByFlow(new Dictionary<string, object>() { { "-1", "-1" } }, law);
        }

        /// <summary>
        /// 获得当前页的总数
        /// </summary>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public int getCountByLike(Page.pa_nf_Law law = null)
        {
            Dictionary<string, object> condition;

            if((law.LTitle!=null) && (law.LTitle != ""))
            {
                condition = getDataLike(new Model.nf_Law() { LTitle=law.LTitle });
                return new DAL.DAL_nf_Law().getCountByLike(condition, law);
            }
            condition = getDataLike(new Model.nf_Law() {});
            return new DAL.DAL_nf_Law().getCountByLike(condition, law);
        }
         
        /// <summary>
        /// 分页·拼接模糊查询的部分
        /// 目的:获得模糊查询的数据
        /// 查询条件:法律名称
        /// </summary>
        /// <param name="specificTemplate"></param>
        /// <returns></returns>
        public Dictionary<string, object> getDataLike(Model.nf_Law law=null)
        {
            Dictionary<string, object> conditions = new Dictionary<string, object>();
            
            //模糊查询条件:法律名称
            if(law.LTitle !=null && law.LTitle != "")
                conditions.Add("LTitle", law.LTitle);

            return conditions;
        }
    /// <summary>
        /// 分页显示数据
        /// </summary>
        /// <param name="law"></param>
        /// <returns></returns>
        public List<Model.nf_Law> getPageDataByFlow(Dictionary<string, object> condition, Page.pa_nf_Law law)
        {
            /*select * from (select ROW_NUMBER() over(order by LId) as rowno,* from nf_Law 
              where IsDelete=2 and LTId=1 and 1=1  and LTitle like '%褥%'  ) t where rowno between 1 and 10
            */
            string sql = "";
            //有模糊查询的业务需求
            if (!condition.ContainsKey("-1"))
            {
                sql = getSqlByConditions("select * from (select ROW_NUMBER() over(order by LId) as rowno,* from nf_Law where IsDelete=2 and LTId=@LTId and 1=1 ", condition,law);
                sql += " ) t where rowno between @first and @second";
            }
            else
                sql = "select * from (select ROW_NUMBER() over(order by LId) as rowno,* from nf_Law where IsDelete=2 and LTId=@LTId and 1=1 ) t where rowno between @first and @second";

            SqlParameter[] parameters =
            {
                new SqlParameter("@LTId",law.LTId),//法律类型编号
                new SqlParameter("@first",law.PageSize * (law.PageNo - 1) + 1),//分页的第一个参数
                new SqlParameter("@second",law.PageSize * law.PageNo)//分页的第二个参数
            };
            List<Model.nf_Law> laws = new List<Model.nf_Law>();
            Model.nf_Law la = null;
            SqlDataReader dr = SqlOption.GetReaderByProc(sql, System.Data.CommandType.Text, parameters);
            while (dr.Read())
            {
                la = new Model.nf_Law()
                {
                    LId=dr["LId"].ToString(),//具体编号
                    LTId =int.Parse(dr["LTId"].ToString()),//法律类型编号
                    IsDelete =int.Parse(dr["IsDelete"].ToString()),//是否删除
                    LTitle=dr["LTitle"].ToString(),//法律标题
                    LContent =dr["LContent"].ToString(),//法律内容
                    LContentText =dr["LContentText"].ToString()//法律文本内容
                };
                laws.Add(la);
            }
            dr.Close();
            return laws;
        }

        /// <summary>
        /// 获得当前页的总数
        /// </summary>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public int getCountByLike(Dictionary<string, object> condition, Page.pa_nf_Law law=null)
        {
            //  select COUNT(*) from nf_Law where IsDelete=2 and LTId=1 and 1=1 and LTitle like'%%'
            string sql = getSqlByConditions("select COUNT(*) from nf_Law where IsDelete=2 and LTId=@LTId and 1=1 ", condition, law);
            SqlParameter[] parameters =
            {
                new SqlParameter("@LTId",law.LTId)//法律类型编号
            };
            if (condition.Keys == null)
            {
                return (int)SqlOption.GetScalar(sql, System.Data.CommandType.Text, parameters);
            }
            return (int)SqlOption.GetScalar(sql, System.Data.CommandType.Text, parameters);
        }

        /// <summary>
        /// 拼接一条SQL语句
        /// 得到部分SQL语句==>and LTitle like'%%'
        /// </summary>
        /// <param name="initSql"></param>
        /// <param name="conditions"></param>
        /// <param name="law"></param>
        /// <returns></returns>
        public string getSqlByConditions(string initSql, Dictionary<string, object> conditions, Page.pa_nf_Law law)
        {
            //查询条件:法律标题(LTitle)
            StringBuilder builder = new StringBuilder(initSql);

            foreach (string filedName in conditions.Keys)
            {
                builder.Append(" and ");
                builder.Append(filedName);

                //如果键值对集合里面中,键和值分别不为空。则,进行添加【法律标题】
                if (filedName == "LTitle" && conditions["LTitle"].ToString() != null && conditions["LTitle"].ToString() != "")
                {
                    builder.Append(" like '%" + law.LTitle + "%' ");
                }

            }
            return builder.ToString();
        }

过多的话,我就不讲了。因为,我的代码是有注释具体说明的。
就在这里简单说说分页模糊查询的本质吧。
总数、当前页数、每页所对应的数据集,这三个条件是必须的条件也是很关键的条件。而layui的分页,也就是获取到这三个最关键的值就可以完成最基本的分页了。

说明:我的代码仅供参考,要是哪位小伙伴觉得还可以优化的地方一定要和我联系哟。😜

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:Age of Ai 设计师:meimeiellie 返回首页
评论 2

打赏作者

云卷云舒~

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值