Asp.Net 中Grid詳解兩種方法使用LigerUI加載數據庫數據填充數據分頁

一、關於LigerUI:

LigerUI 是基於jQuery 的UI框架,其核心設計目標是快速開發、使用簡單、功能強大、輕量級、易擴展。簡單而又強大,致力於快速打造Web前端界面解決方案,能夠應用於.net,jsp,php等等web服務器環境。javascript

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

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

  官網百度雲盤最新下載地址:https://pan.baidu.com/s/1o83vRZkhtml

二、在MVC中使用LigerUI 填充Grid

2.一、新建一個空的MVC項目 把下載框架中Source文件夾下面的Lib目錄複製到項目根目錄,記住是Lib整個目錄,爲了防止文件名重複將他重命名一下以下圖所示

 

2.二、新建一個控制Home,在Home控制器中添加對應的視圖

 

2.三、在視圖裏添加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.五、控制器裏面的不分頁的代碼: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.六、服務器分頁要把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>

 

後臺控制器java

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);
        }
    }

 

三、在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判斷加載方法還能夠(這個是題外話了)jquery

3.二、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裏面的實體類web

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; }
    }

 

效果sql

這個裏面的內容是網絡爬蟲抓取的  有些html字符因此顯示的不統一。這個也是在本地分頁的不過我對裏面的字段都作了截取30個字符 不截取會很卡。算是一個小小的優化吧json

四、總結:細節決定成敗,思路決定出路,態度決定一切。

這個Grid在html頁面裏面實現度娘了好多都沒有找到相關的Demo,本身寫一個留着之後看吧!弄了一夜剛剛看到效果,關於碰到的錯誤只能說明當時沒有好好看官方的API,LigerUI這個表格裏面還有不少功能慢慢的去研究 先把雛形弄出來,由於公司也在用這個,裏面的都是寫好的,剛來公司不久有時間就看看。有時間在弄裏面的搜索功能,,ligerGrid爲的單元格渲染器等等。如今想真的是學無止境  哈哈還有好多。

剛畢業的我不知不覺已通過了一年,感受一年仍是沒有多少長進。紙上得來終覺淺,絕知此事要躬行。也許有的路只有走下去才知道會碰見什麼樣的風景!夜深了差很少也該睡覺了。。。

相關文章
相關標籤/搜索