看到下圖,是通過Jqgrid實現表格式資料的基本增刪查改的操作。表格式資料增刪改是一般公司專屬應用程式系統開發的常見功能,不過不同的是這個表格式資料來源是非關係型的資料庫MongoDB。nosql雖然概念新穎,但是MongoDB基本應用實現起來還是比較輕鬆的,甚至代碼比基本的ADO.net訪問關係資料來源還要簡潔。由於其本身的“非關係”的資料存放區方式,使得對象關係映射這個環節對於MongoDB來講顯得毫無意義,因此我們也不會對MongoDB引入所謂的“ORM”架構。
下面我們將逐步講解怎麼在MVC模式下將MongoDB資料讀取,並展示在前台Jqgrid表格上。這個“簡易系統”的基本設計思想是這樣的:我們在視圖層展示表格,Jqgrid相關Js邏輯全部放在一個Js檔案中,控制層實現了“增刪查改”四個業務,MongoDB的基本資料訪問放在了模型層實現。下面我們一步步實現。 一、實現視圖層Jqgrid表格邏輯
首先,我們建立一個MVC空白項目,添加好jQuery、jQueryUI、Jqgrid的前端架構代碼:
然後在Views的Home檔案夾下建立視圖“Index.aspx”,在視圖的body標籤中添加如下HTML代碼: view source print ?
接著建立Scripts\Home檔案夾,在該目錄建立“Index.js”檔案,並再視圖中引用,代碼如下: show source view source print ?
| 001 |
jQuery(document).ready(function () { |
| 004 |
jQuery("#table1").jqGrid({ |
| 005 |
url: '/Home/UserList', |
| 008 |
colNames: ['登入名稱', '姓名', '年齡', '手機號', '郵箱地址', '操作'], |
| 010 |
{ name: 'UserId', index: 'UserId', width: 180, editable: true }, |
| 011 |
{ name: 'UserName', index: 'UserName', width: 200, editable: true }, |
| 012 |
{ name: 'Age', index: 'Age', width: 150, editable: true }, |
| 013 |
{ name: 'Tel', index: 'Tel', width: 150, editable: true }, |
| 014 |
{ name: 'Email', index: 'Email', width: 150, editable: true }, |
| 015 |
{ name: 'Edit', index: 'Edit', width: 150, editable: false, align: 'center' } |
| 020 |
rowList: [5, 10, 20], |
| 026 |
}).navGrid('#div1', { edit: false, add: false, del: false }) |
| 027 |
.navButtonAdd('#div1', { |
| 029 |
buttonicon: "ui-icon-add", |
| 030 |
onClickButton: function () { |
| 031 |
var id = $("#table1").getGridParam("selrow"); |
| 036 |
if (id == "newId") return; |
| 037 |
$("#table1").editRow(id); |
| 038 |
$("#table1").find("#" + id + "_UserId").attr("readonly","readOnly"); |
| 039 |
$("#table1").setCell(id, "Edit", "<input id='Button1' type='button' value='提交' onclick='Update(\"" + id + "\")' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"" + id + "\")' />"); |
| 041 |
}).navButtonAdd('#div1', { |
| 043 |
buttonicon: "ui-icon-del", |
| 044 |
onClickButton: function () { |
| 045 |
var id = $("#table1").getGridParam("selrow"); |
| 052 |
}).navButtonAdd('#div1', { |
| 054 |
buttonicon: "ui-icon-add", |
| 055 |
onClickButton: function () { |
| 056 |
$("#table1").addRowData("newId", -1); |