Asp.Net 中Grid详解两种方法使用LigerUI加载数据库数据填充数据分页

1、关于LigerUI:

LigerUI 是基于jQuery 的UI框架,其核心设计目标是快速开发、使用简单、功能强大、轻量级、易扩展。简单而又强大,致力于快速打造Web前端界面解决方案,可以应用于.net,jsp,php等等web服务器环境。

  LigerUI演示地址:http://www.ligerui.com

  LigerUI API地址:http://api.ligerui.com/

  官网百度云盘最新下载地址:https://pan.baidu.com/s/1o83vRZk

2、在MVC中使用LigerUI 填充Grid

2.1、新建一个空的MVC项目 把下载框架中Source文件夹下面的Lib目录复制到项目根目录,记住是Lib整个目录,为了防止文件名重复将他重命名一下如下图所示

 

2.2、新建一个控制Home,在Home控制器中添加对应的视图

 

2.3、在视图里添加Grid所需要的JS跟CSS,这里主要的就是前面4个路径不能写错,这里特别提示一下  不要引用MVC创建项目里Script文件夹下面的jQuery  我的用了就出错了  问题还没有找到  我直接删除了里面的js  也没有引用布局。

 

2.4不分页或者本地分页的视图代码:里面的代码都通俗易懂通过URL到控制器里面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="~/ScriptStyle/ligerUI/skins/Aqua/css/ligerui-all.css" />
    <script src="~/ScriptStyle/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/core/base.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerGrid.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/ligerui.min.js" type="text/javascript"></script>


    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerResizable.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerCheckBox.js" type="text/javascript"></script>
    <style type="text/css">
        .divmain {
            width: 1200px;
            margin: 0 auto;
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            //本地分页
            $("#MainGridTest").ligerGrid({
                width: 1000,
                columns: [
                    { display: "学号", name: "Number" },
                    { display: "流水号", name: "WaterID" },
                    { display: "地点", name: "Place" },
                    { display: "金钱", name: "Money" },
                    { display: "操作员", name: "People" },
                    { display: "时间", name: "Times",type:'date',format:'yyyy年MM月dd日 hh:mm:ss'},
                    { display: "备注", name: "Depict" }
                ],
                url: "/Home/GetDataNoPage",
                pageSize: 30,
                usePage: true,
                dataAction: "local",//本地分页
                pageSizeOptions: [10, 20, 30, 50, 100]//可指定每页页面大小
            });
            
        });
    </script>

</head>
<body>
    <br /><br /><br />
    <h2 style="text-align:center;">MVC LigerUI显示测试不分页或者是本地分页</h2><br />
    <div class="divmain" id="MainGridTest"></div>
    
</body>
</html>

 

2.5、控制器里面的不分页的代码:ligerGrid显示数据采用 json对象,注意默认情况下grid要求的json数据格式如下:{Rows:[{},{}],Total:2};    我在这里搞了好多次,一般的Json取回来都是[{},{},{}]这样的格式 这个特别注意一下

 public ActionResult GetDataNoPage()
        {
           
            string _sql = "select top 200 Number, WaterID, Place, Money, State, People, Times, Depict from Record";
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=.;Initial Catalog=OneCardSystem;Integrated Security=True";
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = _sql;
            cmd.Connection = conn;

            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            sda.Fill(ds);

            var datas =ds.Tables[0].Rows;
            List<ModleSt> list = new List<ModleSt>();
            var total = datas.Count;
            foreach (DataRow item in datas)
            {
                var act = new ModleSt()
                {
                    Number= item["Number"].ToString(),
                    WaterID= item["WaterID"].ToString(),
                    Place= item["Place"].ToString(),
                    Money=Convert.ToDouble( item["Money"]),
                    State= item["State"].ToString(),
                    People= item["People"].ToString(),
                    Times=Convert.ToDateTime(item["Times"].ToString()),
                    Depict= item["Depict"].ToString(),
                };
                list.Add(act);
            }
            var GetDatt = new {
                Rows=list,
                Total=total
            };
            return Json(GetDatt);
        }

 

我这里没有封装失sqlDB类写的有点多了,注意后面一定要返回Json格式  要加上Rows跟total  total就是数据的数量也就是长度。可以看到效果是这样的。这个是本地分页,数据量小感觉不到 数据量大的时候回很吃内存的。ModleSt  是这个数据的实体类

2.6、服务器分页要把Grid里面的dataAction: "local",注释了这个属性就这样 为true的时候本地会自动分页

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="~/ScriptStyle/ligerUI/skins/Aqua/css/ligerui-all.css" />
    <script src="~/ScriptStyle/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/core/base.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerGrid.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/ligerui.min.js" type="text/javascript"></script>


    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerResizable.js" type="text/javascript"></script>
    <script src="~/ScriptStyle/ligerUI/js/plugins/ligerCheckBox.js" type="text/javascript"></script>
    <style type="text/css">
        .divmain {
            width: 1200px;
            margin: 0 auto;
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            
            //服务器分页
            $("#MainGridTestTOW").ligerGrid({
                width: 1000,
                columns: [
                    { display: "学号", name: "Number" },
                    { display: "流水号", name: "WaterID" },
                    { display: "地点", name: "Place" },
                    { display: "金钱", name: "Money" },
                    { display: "操作员", name: "People" },
                    { display: "时间", name: "Times", type: 'date', format: 'yyyy年MM月dd日 hh:mm:ss' },
                    { display: "备注", name: "Depict" }
                ],
                url: "/Home/GetDataUsePage",
                pageSize: 30,
                usePage: true,
                //dataAction: "local",
                rownumber: true,
                pageSizeOptions: [10, 20, 30, 50, 100]//可指定每页页面大小
            });
        });
    </script>

</head>
<body>
    
    <br /><br /><br />
    <h2 style="text-align:center;">MVC LigerUI显示测试服务器分页</h2><br />
    <div class="divmain" id="MainGridTestTOW"></div>
</body>
</html>

 

后台控制器

public ActionResult GetDataUsePage()
        {

            //排序的字段名
            string SortName = Request.Params["sortname"];
            //排序的方向
            string SortOrder = Request.Params["sortorder"];
            //当前页
            int PageNow = Convert.ToInt32(Request.Params["page"]);
            //每页显示的记录数
            int pagesize = Convert.ToInt32(Request.Params["pagesize"]);

            string _sql = "select  Number, WaterID, Place, Money, State, People, Times, Depict from Record";
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=.;Initial Catalog=OneCardSystem;Integrated Security=True";
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = _sql;
            cmd.Connection = conn;

            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            sda.Fill(ds);
            var datas = ds.Tables[0].Rows;
            List<ModleSt> list = new List<ModleSt>();
            var total = datas.Count;
            foreach (DataRow item in datas)
            {
                var act = new ModleSt()
                {
                    Number = item["Number"].ToString(),
                    WaterID = item["WaterID"].ToString(),
                    Place = item["Place"].ToString(),
                    Money = Convert.ToDouble(item["Money"]),
                    State = item["State"].ToString(),
                    People = item["People"].ToString(),
                    Times = Convert.ToDateTime(item["Times"].ToString()),
                    Depict = item["Depict"].ToString(),
                };
                list.Add(act);
            }

            //模拟排序操作字段Number  学号
            if (SortOrder == "desc")
                list = list.OrderByDescending(c => c.Number).ToList();
            else
                list = list.OrderBy(c => c.Number).ToList();

            IList<ModleSt> usePageList = new List<ModleSt>();
            //这里模拟分页操作
            for (var i = 0; i < total; i++)
            {
                if (i >= (PageNow - 1) * pagesize && i < PageNow * pagesize)
                {
                    usePageList.Add(list[i]);
                }
            }
            var usePagedata = new { Rows = usePageList, Total = total };
            return Json(usePagedata);
        }
    }

 

3、在html里面通过ashx处理文件加载数据

3.1静态页面代码:一样班的加上JS跟css文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="../ScriptStyle/ligerUI/skins/Aqua/css/ligerui-all.css" />
    <script type="text/javascript" src="../ScriptStyle/jquery/jquery-1.9.0.min.js"></script>
    <script type="text/javascript" src="../ScriptStyle/ligerUI/js/core/base.js"></script>
    <script type="text/javascript" src="../ScriptStyle/ligerUI/js/plugins/ligerGrid.js"></script>

    <script src="../ScriptStyle/ligerUI/js/plugins/ligerResizable.js" type="text/javascript"></script>
    <script src="../ScriptStyle/ligerUI/js/plugins/ligerCheckBox.js" type="text/javascript"></script>

    <script type="text/javascript" src="../ScriptStyle/DataOne.js"></script>
    <style type="text/css">
        .divmain {width: 100%;margin: 0 auto;text-align: center; padding:20px; }
    </style>
    <script type="text/javascript">
        $(function () {
            $("#MainGridTest").ligerGrid({
                //width: 1000,
                columns: [
                    { display: "ID", name: "ID" },
                    { display: "推荐数", name: "Recommend" },
                    { display: "标题", name: "Title" },
                    { display: "内容", name: "Contents" },
                    { display: "介绍", name: "Introduce" },
                    { display: "原文网址", name: "WebHref" },
                    { display: "增加时间", name: "GetTime" },
                    { display: "文章发表时间", name: "ArticleTime" }
                ],
                url: "../Admin_Ajax/GetData_TypeJson.ashx",
                pageSize: 30,
                usePage: true,
                dataAction: "local",
                pageSizeOptions: [10, 20, 30, 50, 100]//可指定每页页面大小
            });
        });

    </script>

</head>
<body>
    <br /><br /><br />
    <h2 style="text-align:center;">html通过ashx获取数据LigerUI显示测试</h2><br />
    <div class="divmain" id="MainGridTest"></div>
</body>
</html>

 

里面的url会儿机指向文件名就可以了 不能知道具体的方法,以前试过了就是不行,只能在里面做case判断加载方法还可以(这个是题外话了)

3.2、ashx页面:我注释的内容就是我最初的方法我以为这样转Json数据后可以获取到值,左弄右弄数据可以取到就是显示不出来,最后还是转为list 在实例在Getdatt里面才出来  前面就说了这个json格式要求就这样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//添加命名空间
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Newtonsoft.Json;
namespace LigerUITest20180523.Admin_Ajax
{
    /// <summary>
    /// GetData_TypeJson 的摘要说明
    /// </summary>
    public class GetData_TypeJson : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string _sql = "select ID,Recommend,SUBSTRING(Title,0,30)AS Title,SUBSTRING(Contents,0,30)AS Contents ,SUBSTRING(Introduce,0,30)AS Introduce ,SUBSTRING(Webhref,0,20)AS WebHref , GetTime,ArticleTime from CnblogsList";
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=.;Initial Catalog=TestBase;Integrated Security=True";
            if(conn.State== ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = _sql;
            cmd.Connection = conn;

            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            sda.Fill(ds);
            //string AppendStr = "{Rows:";
            //AppendStr = AppendStr + JsonConvert.SerializeObject(ds.Tables[0]).ToString();
            //AppendStr = AppendStr + ",Total:20}";
            //context.Response.Write(JsonConvert.SerializeObject(AppendStr));

            var datas = ds.Tables[0].Rows;
            List<ModleSt> list = new List<ModleSt>();
            var total = datas.Count;
            foreach (DataRow item in datas)
            {
                var act = new ModleSt()
                {
                    ID =Convert.ToInt32( item["ID"].ToString()),
                    Recommend = Convert.ToInt32(item["Recommend"].ToString()),
                    Title = item["Title"].ToString(),
                    Contents = item["Contents"].ToString(),
                    Introduce = item["Introduce"].ToString(),
                    WebHref = item["WebHref"].ToString(),
                    GetTime = Convert.ToDateTime(item["GetTime"].ToString()),
                    ArticleTime = Convert.ToDateTime(item["ArticleTime"].ToString()),
                };
                list.Add(act);
            }
            var GetDatt = new
            {
                Rows = list,
                Total = total
            };
            context.Response.Write(JsonConvert.SerializeObject(GetDatt));
        }
        public class ModleSt
        {
            public int Recommend { get; set; }
            public int ID { get; set; }
            public string Title { get; set; }
            public string Contents { get; set; }
            public string Introduce { get; set; }
            public string WebHref { get; set; }
            public DateTime GetTime { get; set; }
            public DateTime ArticleTime { get; set; }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

MVC里面的实体类

public class ModleSt
    {
        public  string Number { get; set; }
        public string WaterID { get; set; }
        public string Place { get; set; }
        public double Money { get; set; }
        public string State { get; set; }
        public string People { get; set; }
        public DateTime Times { get; set; }
        public string Depict { get; set; }
    }

 

效果

这个里面的内容是网络爬虫抓取的  有些html字符所以显示的不统一。这个也是在本地分页的不过我对里面的字段都做了截取30个字符 不截取会很卡。算是一个小小的优化吧

4、总结:细节决定成败,思路决定出路,态度决定一切。

这个Grid在html页面里面实现度娘了好多都没有找到相关的Demo,自己写一个留着以后看吧!弄了一晚上刚刚看到效果,关于碰到的错误只能说明当时没有好好看官方的API,LigerUI这个表格里面还有很多功能慢慢的去研究 先把雏形弄出来,因为公司也在用这个,里面的都是写好的,刚来公司不久有时间就看看。有时间在弄里面的搜索功能,,ligerGrid为的单元格渲染器等等。现在想真的是学无止境  哈哈还有好多。

刚毕业的我不知不觉已经过了一年,感觉一年还是没有多少长进。纸上得来终觉浅,绝知此事要躬行。也许有的路只有走下去才知道会遇见什么样的风景!夜深了差不多也该睡觉了。。。

 

posted @ 2018-05-24 01:36  魏杨杨  阅读(2247)  评论(5编辑  收藏  举报
行到水穷处,坐看云起时!转载声明:技术需要共享,欢迎转载!但请注明版权及出处!