使用jqGrid設計網頁

by vivid 2. 五月 2018 10:01

.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號: N180519501
出刊日期: 2018/5/2

本文將介紹如何在MVC 5的專案之中,整合jqGrid以表格的方式呈現從資料庫取回的資料,並且能夠根據不同欄位排序、設計資料分頁等功能。

jqGrid是一個歷史悠久的前端JavaScript開發元件,第一版在2007年問市,歷經版本演變,目前若將之用於商業用途需付費,如後端使用PHP技術開發網站,可參考以下官網:「http://guriddo.net」。若後端使用微軟ASP.NET MVC、ASP.NET Core相關技術,可參考以下官網:「http://trirand.net/」。

以下以Step-by-Step方式說明如何在ASP.NET MVC 5專案中分別使用Bootstrap與jQuery UI整合jqGrid來設計網頁。

 

建立ASP.NET MVC 5專案

啟動Visual Studio 2017開發環境,從「File」-「New」-「Project」,在「New Project」對話盒中,確認視窗上方.NET Framework的目標版本為「.NET Framework 4.6.1以上」,選取左方「Installed」-「Templates」-「Visual C#」程式語言,從「Web」分類中,選取「ASP.NET Web Application (.NET Framework)」,設定專案名稱,如「GridDemo」、設定專案存放路徑,然後按下「OK」鍵,請參考下圖所示:

clip_image002

圖 1:建立ASP.NET MVC 5專案。

在「New ASP.NET Web Application」對話盒中選取「Empty」,勾選下方的「MVC」項目,然後按下「OK」按鈕建立專案,請參考下圖所示:

clip_image004

圖 2:選取「Empty」MVC專案。

安裝必要套件

接下來的步驟要整合jQuery、Bootstrap與jqGrid套件,我們需要在專案中安裝以下版本的套件:

· jQuery: 3.3.1版。

· bootstrap:3.3.7版。jqGrid也支援Bootstrap 4版,本文以3.3.7版為主。

· jqGrid:5.2.0版。

從Visual Studio 2017開發工具 -「Solution Explorer」視窗 - 專案名稱上方按滑鼠右鍵,從快捷選單選擇「Manage Nuget Packages」,開啟對話盒,接著選取視窗上方的「Browse」分頁,並在上方的文字方塊中輸入關鍵字「jQuery」進行篩選,下方便會列出可安裝的套件,選取其中的「jQuery」套件,在右方的下拉式清單方塊中,選取要使用的「3.3.1」版,然後按下「Install」按鈕進行安裝,請參考下圖所示:

clip_image006

圖 3:安裝「jQuery」套件。

下一步驟會看到安裝確認視窗,直接按「OK」按鈕,請參考下圖所示:

clip_image008

圖 4:確認安裝。

重複上面的步驟,在上方的文字方塊中輸入關鍵字「bootstrap」進行篩選,選取安裝「Bootstrap」套件,在右方的下拉式清單方塊中,選取要使用的「3.3.7」版,然後按下「Install」按鈕,請參考下圖所示:

clip_image010

圖 5:安裝「bootstrap」套件。

加入jqGrid相關檔案

若使用Visual Studio NuGet工具下載「Triand.jqGrid」套件,預設只包含整合jQuery UI樣式的「ui.jqgrid.css」檔案(支援jQuery UI),欠缺整合Bootstrap樣式的「ui.jqgrid-bootstrap.css」檔案,且也只能搜尋到「Triand.jqGrid 4.6.0」版,無法找到本文想用的「5.2.0」版,請參考下圖所示:

clip_image012

圖 6:Triand.jqGrid 套件。

因此,此步驟改成手動從官網下載「jqSuiteASPNET_MVC_5_2_0_0_Files.zip」檔案,再將必要檔案加入專案之中。從官網「http://trirand.net/download.aspx」,選取「ASP.NET MVC」分類下的「DOWNLOAD」按鈕進行下載,請參考下圖所示:

clip_image014

圖 7:手動下載jqGrid。

解壓縮從官網下載的「jqSuiteASPNET_MVC_5_2_0_0_Files.zip」檔案,找到以下檔案,將之加入專案中的「Scripts」資料夾:

· grid.locale-tw.js

· jquery.jqGrid.min.js

找到以下檔案,將之加入專案中的「Content:資料夾:

· ui.jqgrid-bootstrap.css

建立ADO.NET實體資料模型

下一步是使用Visual Studio的功能來定義ADO.NET實體資料模型,然後利用Entity Framework Database First技術自動根據資料庫結構描述資訊來建立模型。在MVC的專案之中,通常將ADO.NET實體資料模型的相關程式置於「Models」資料夾之中。

從Visual Studio 2017開發工具 -「Solution Explorer」- 專案-「Models」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒。

在「Add New Item」對話盒選取「ADO.NET Entity Data Model」項目,設定名稱為「PubsModel」,請參考下圖所示:

clip_image016

圖 8:建立ADO.NET實體資料模型。

然後在「Entity Data Model Wizard」 視窗,選取「EF Designer from Database」項目,按下「Next」按鈕,請參考下圖所示:

clip_image018

圖 9:選取「EF Designer from Database」項目。

在「Choose Your Data Connection」的步驟視窗選擇連接到「Pubs」資料庫,然後按下「Next」按鈕,請參考下圖所示:

clip_image020

圖 10:連接到「Pubs」資料庫。

在 「Choose Your Version」 步驟,請選擇「Entity Framework 6.x」,按下「Next」按鈕,請參考下圖所示:

clip_image022

圖 11:選擇「Entity Framework 6.x」版本。

在 「Choose Your Database Objects and Settings」步驟 ,展開「Table」à「dbo」勾選「Authors」,並勾選下方的「Pluralize or singularize generated object names」。如下圖所示,並按下「Finish」按鈕完成 「Entity Data Model Wizard」 的設計步驟。

clip_image024

圖 12:勾選資料表。

選取Visual Studio 開發工具「Build」-「Build Solution」項目編譯目前的專案,確認程式碼能正確編譯。

 

設計控制器

從Visual Studio 2017開發工具 -「Solution Explorer」視窗- 專案 -「Controllers」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「Controller」,開啟「Add Scaffold」對話盒。選取「MVC 5 Controller - Empty」,然後按下「Add」按鈕,請參考下圖所示:

clip_image026

圖 13:新增控制器。

在「Add Controller」對話盒中,設定控制器名稱為「HomeController」;然後按下「Add 」按鈕,Visual Studio 2017便會在「Controllers」資料夾下,新增HomeController.cs,包含控制器程式碼基本的程式碼,請參考下圖所示:

clip_image028

圖 14:新增HomeController控制器。

取回JSON資料

在新增的「HomeController.cs」檔案中加入程式碼。於「HomeController」類別中加入一個「GetData」方法可以從資料庫中查詢特定分頁的資料,然後回傳JSON格式資料供前端使用:

using GridDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GridDemo.Controllers {
  public class HomeController : Controller {
    pubsEntities _db = new pubsEntities( );
    public ActionResult Index( ) {
      return View( );
    }

    public JsonResult GetData( int rows = 10 , string sord = "asc" , string sidx = "au_id" , int page = 1 ) {
      IQueryable<author> authors = _db.authors;

      switch ( sidx ) {
        case "au_lname":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_lname ) : authors.OrderByDescending( a => a.au_lname );
          break;
        case "au_fname":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_fname ) : authors.OrderByDescending( a => a.au_fname );
          break;
        case "phone":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.phone ) : authors.OrderByDescending( a => a.phone );
          break;
        case "address":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.address ) : authors.OrderByDescending( a => a.address );
          break;
        case "city":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.city ) : authors.OrderByDescending( a => a.city );
          break;
        default:
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_id ) : authors.OrderByDescending( a => a.au_id );
          break;
      }

      int pageSize = rows;
      int totalRecords = authors.Count( );
      int totalPages = (int) Math.Ceiling( (float) totalRecords / (float) pageSize );

      var jsonData = new {
        total = totalPages ,
        page = page ,
        records = totalRecords ,
        rows = authors.Skip( ( page - 1 ) * pageSize ).Take( pageSize )
      };

      return Json( jsonData , JsonRequestBehavior.AllowGet );
    }
  }
}

 

測試伺服端資料

選取Visual Studio開發工具,「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。然後按CTRL+F5執行網站,忽略掉網頁出現的錯誤訊息,直接在Visual Studio自動啟動的瀏覽器,輸入以下網址查詢出10筆作者資料(請注意:埠號可能會依據實際上的操作而有所不同,如以下的「64195」,請修改為實際的埠號):

http://localhost:64195/home/GetData?page=1&rows=10&sord=asc

若沒有問題瀏覽器會收到以下JSON格式的資料:

{

"total": 3, "page": 1, "records": 23,

"rows":

[

{ "au_id": "172-32-1176", "au_lname": "White", "au_fname": "Johnson", "phone": "408 496-7223", "address": "10932 Bigge Rd.", "city": "Menlo Park", "state": "CA", "zip": "94025", "contract": true },

{ "au_id": "213-46-8915", "au_lname": "Green", "au_fname": "Marjorie", "phone": "415 986-7020", "address": "309 63rd St. #411", "city": "Oakland", "state": "CA", "zip": "94618", "contract": true },

{ "au_id": "238-95-7766", "au_lname": "Carson", "au_fname": "Cheryl", "phone": "415 548-7723", "address": "589 Darwin Ln.", "city": "Berkeley", "state": "CA", "zip": "94705", "contract": true },

{ "au_id": "267-41-2394", "au_lname": "O\u0027Leary", "au_fname": "Michael", "phone": "408 286-2428", "address": "22 Cleveland Av. #14", "city": "San Jose", "state": "CA", "zip": "95128", "contract": true },

{ "au_id": "274-80-9391", "au_lname": "Straight", "au_fname": "Dean", "phone": "415 834-2919", "address": "5420 College Av.", "city": "Oakland", "state": "CA", "zip": "94609", "contract": true },

{ "au_id": "341-22-1782", "au_lname": "Smith", "au_fname": "Meander", "phone": "913 843-0462", "address": "10 Mississippi Dr.", "city": "Lawrence", "state": "KS", "zip": "66044", "contract": false },

{ "au_id": "409-56-7008", "au_lname": "Bennet", "au_fname": "Abraham", "phone": "415 658-9932", "address": "6223 Bateman St.", "city": "Berkeley", "state": "CA", "zip": "94705", "contract": true },

{ "au_id": "427-17-2319", "au_lname": "Dull", "au_fname": "Ann", "phone": "415 836-7128", "address": "3410 Blonde St.", "city": "Palo Alto", "state": "CA", "zip": "94301", "contract": true },

{ "au_id": "472-27-2349", "au_lname": "Gringlesby", "au_fname": "Burt", "phone": "707 938-6445", "address": "PO Box 792", "city": "Covelo", "state": "CA", "zip": "95428", "contract": true },

{ "au_id": "486-29-1786", "au_lname": "Locksley", "au_fname": "Charlene", "phone": "415 585-4620", "address": "18 Broadway Av.", "city": "San Francisco", "state": "CA", "zip": "94130", "contract": true }

]

}

這個範例程式的執行結果參考如下:

clip_image030

圖 15:取回第一頁作者資料。

建立Index檢視

建立「Index」檢視。將游標停留在「HomeController」控制器程式設計畫面「Index」方法之中,按滑鼠右鍵,從快捷選單選取「Add View」,請參考下圖所示:

clip_image032

圖 16:建立Index檢視。

在「Add View」對話盒中,設定以下項目:

· View name:「Index」。

· Template:「Empty (without model)」。

· 清除勾選所有核取方塊。

然後按下「Add」按鈕,請參考下圖所示:

clip_image034

圖 17:建立Index檢視。

設計Index檢視

在「Index.cshtml」檔案中加入以下程式碼:

@{
  Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name = "viewport" content = "width=device-width" />
    <title> Index </title>
    <link href = "~/Content/bootstrap.min.css" rel = "stylesheet" />
    <link href = "~/Content/ui.jqgrid-bootstrap.css" rel = "stylesheet" />
</head>
<body>
    <h2> JQGrid Demo </h2>
    <div style = "margin-left:20px" >
        <table id = "grid"> </table>
        <div id = "pager">
        </div>
    </div>
    <script src = "~/Scripts/jquery-3.3.1.min.js"> </script>
    <script src = "~/Scripts/grid.locale-tw.js"> </script>
    <script src = "~/Scripts/jquery.jqGrid.min.js"> </script>
    <script>
        $(function () {
            var grid = $('#grid');
            grid.jqGrid({
                url: '/Home/GetData/',
                datatype: 'json',
                styleUI: 'Bootstrap',
                mtype: 'GET',
                colModel: [
                    { name: 'au_id', label: '編號', width: 40, align: 'left' },
                    { name: 'au_lname', label: '作者姓氏', width: 40, align: 'left' },
                    { name: 'au_fname', label: '作者名稱', width: 40, align: 'left' },
                    { name: 'phone', label: '電話號碼', width: 40, align: 'left' },
                    { name: 'address', label: '地址', width: 40, align: 'left' },
                    { name: 'city', label: '城市', width: 20, align: 'left' }
                ],
                pager: '#pager',
                width: 780,
                height: 'auto',
                rowNum: 10,
                sortname: 'au_id',
                sortorder: "asc",
                viewrecords: true,
                caption: '作者清單'
            });
        });
    </script>
</body>
</html>

 

這個網頁執行時會利用jQuery送出AJAX請求,叫用伺服端的「/Home/Index」方法從資料庫取回JSON資料,將資料提供給jqGrid顯示。在此要注意的是需要設定「styleUI」為「Bootstrap」。

最後,選取Visual Studio 開發工具「Build」-「Build Solution」項目編譯目前的專案,確認程式碼能正確編譯。

在Visual Studio開發工具,按CTRL+F5執行網站首頁(請注意:埠號可能會依據實際上的操作而有所不同,請修改為實際的埠號),然後在瀏覽器輸入以下URL:

http://localhost:64195/home/

這個範例程式的執行結果參考如下:

clip_image036

圖 18:整合Bootstrap、jqGrid網頁。

整合jQuery UI樣式

若要整合jQuery、jQuery UI與jqGrid套件來呈現資料,我們需要在專案中安裝以下版本的套件:

· jQuery: 3.3.1版。

· jQuery.UI.Combined:1.12.1版。

· jqGrid:5.2.0版。

你可以使用Visual Studio 2017安裝jQuery UI套件,從Visual Studio 2017開發工具 -「Solution Explorer」視窗 - 專案名稱上方按滑鼠右鍵,從快捷選單選擇「Manage Nuget Packages」,開啟對話盒,接著選取視窗上方的「Browse」分頁,並在上方的文字方塊中輸入關鍵字「jqueryui」進行篩選,下方便會列出可安裝的套件,選取其中的「jQuery.UI.Combined」套件,在右方的下拉式清單方塊中,選取要使用的「1.12.1」版,然後按下「Install」按鈕進行安裝,請參考下圖所示:

clip_image038

圖 19:安裝「jQuery UI」套件。

開發工具會自動在「Content」-「Themes」資料夾中加入樣式表,並在「Scripts」資料夾中加入「jquery-ui-1.12.1.min.js」檔案。

手動將jqgrid提供的檔案以下檔案加入「Content」資料夾:

· ui.jqgrid.css

修改「HomeController」類別程式碼,加入一個「JGridUI」方法:

public ActionResult JGridUI( ) {
  return View( );
}

目前「HomeController」控制器程式如下:

using GridDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GridDemo.Controllers {
  public class HomeController : Controller {
    pubsEntities _db = new pubsEntities( );
    public ActionResult Index( ) {
      return View( );
    }

    public ActionResult JGridUI( ) {
      return View( );
    }

    public JsonResult GetData( int rows = 10 , string sord = "asc" , string sidx = "au_id" , int page = 1 ) {
      IQueryable<author> authors = _db.authors;

      switch ( sidx ) {
        case "au_lname":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_lname ) : authors.OrderByDescending( a => a.au_lname );
          break;
        case "au_fname":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_fname ) : authors.OrderByDescending( a => a.au_fname );
          break;
        case "phone":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.phone ) : authors.OrderByDescending( a => a.phone );
          break;
        case "address":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.address ) : authors.OrderByDescending( a => a.address );
          break;
        case "city":
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.city ) : authors.OrderByDescending( a => a.city );
          break;
        default:
          authors = ( sord == "asc" ) ? authors.OrderBy( a => a.au_id ) : authors.OrderByDescending( a => a.au_id );
          break;
      }

      int pageSize = rows;
      int totalRecords = authors.Count( );
      int totalPages = (int) Math.Ceiling( (float) totalRecords / (float) pageSize );

      var jsonData = new {
        total = totalPages ,
        page = page ,
        records = totalRecords ,
        rows = authors.Skip( ( page - 1 ) * pageSize ).Take( pageSize )
      };

      return Json( jsonData , JsonRequestBehavior.AllowGet );
    }
  }
}

 

建立「JGridUI」檢視。將游標停留在「HomeController」控制器程式設計畫面「JGridUI」方法之中,按滑鼠右鍵,從快捷選單選取「Add View」,請參考下圖所示:

clip_image040

圖 20:建立JGridUI檢視。

在「Add View」對話盒中,設定以下項目:

· View name:「JGridUI」。

· Template:「Empty (without model)」。

· 清除勾選所有核取方塊。

然後按下「Add」按鈕。修改JGridUI檢視程式如下,叫用「jqGrid」方法時移除「styleUI」設定,那麼預設就會採用jQuery UI來呈現樣式:

@{
  Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name = "viewport" content = "width=device-width" />
    <title>Index</title>
    <link href = "~/Content/themes/base/all.css" rel = "stylesheet" />
    <link href = "~/Content/ui.jqgrid.css" rel = "stylesheet" />
</head>
<body>
    <h2>JQGrid Demo</h2>
    <div style = "margin-left:20px">
        <table id = "grid"></table>
        <div id = "pager">
        </div>
    </div>
    <script src = "~/Scripts/jquery-3.3.1.min.js"></script>
    <script src = "~/Scripts/grid.locale-tw.js"></script>
    <script src = "~/Scripts/jquery.jqGrid.min.js"></script>
    <script>
        $(function () {
            var grid = $('#grid');
            grid.jqGrid({
                url: '/Home/GetData/',
                datatype: 'json',
                mtype: 'GET',
                colModel: [
                    { name: 'au_id', label: '編號', width: 40, align: 'left' },
                    { name: 'au_lname', label: '作者姓氏', width: 40, align: 'left' },
                    { name: 'au_fname', label: '作者名稱', width: 40, align: 'left' },
                    { name: 'phone', label: '電話號碼', width: 40, align: 'left' },
                    { name: 'address', label: '地址', width: 40, align: 'left' },
                    { name: 'city', label: '城市', width: 20, align: 'left' }
                ],
                pager: '#pager',
                width: 780,
                height: 'auto',
                rowNum: 10,
                sortname: 'au_id',
                sortorder: "asc",
                viewrecords: true,
                caption: '作者清單'
            });
        });
    </script>
</body>
</html>

 

選取Visual Studio 開發工具「Build」-「Build Solution」項目編譯目前的專案,確認程式碼能正確編譯。

在Visual Studio開發工具,按CTRL+F5執行網站首頁(請注意:埠號可能會依據實際上的操作而有所不同,請修改為實際的埠號),然後在瀏覽器輸入以下URL:

http://localhost:64195/home/JGridUI

這個範例程式的執行結果參考如下:

clip_image042

圖 21:整合jQuery UI顯示樣式。

總結

最後整理jqGrid提供功能清單如下:

  • 根據欄位進行資料排序、分頁、搜尋、篩選功能。
  • 提供Search Control在表頭提供下拉式清單(dropdowns)、DatePicker、AutoComplete、Checkbox、自訂…等等。
  • 表頭提供Action Menu,可以在表頭提供選單以執行排序、篩選、資料分組、顯示欄位、隱藏欄位、凍結欄位。
  • 提供Virtual Scrolling功能,右方捲軸出現目前顯示筆數,如「34 out of 300」。
  • 資料可以從伺服器一次載入,後續排序、分頁、搜尋、篩選都在用戶端處理。
  • 可將目前狀態儲存在本機儲存體(local storage),並從本機儲存體載入。
  • 支援多國語言。
  • 支援Right To Left (RTL) 顯示。
  • 使用Cell Formatters自訂顯示。
  • 使用拖放方式變動欄位順序。
  • 使用拖曳方式變更欄位寬度。
  • 資料橫列提供選單(Context Menu)。
  • 自訂工具列按鈕。
  • 編輯對話盒,以修改資料。
  • 搭配新增對話盒,可新增資料。
  • 資料橫列可以顯示Context Menu,以執行資料新增、刪除或編輯作業。
  • 可匯出成Excel、CSV、PDF格式。
  • 多階層顯示,即表格橫列中可以再含表格(巢狀顯示)。
  • 支援響應式網頁,如Bootstrap樣式。
  • 支援jQuery UI樣式
  • 整合TreeView,可以從TreeView拖曳節點到jqGrid。

目前評分 5.0 , 共有 2 人參與

  • Currently 5.0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET Magazine國際中文電子雜誌 | .NET Framework | ASP.NET MVC | 許薰尹Vivid Hsu

NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List