MongoDB學(xué)習(xí)筆記(三) 在MVC模式下通過(guò)Jqgrid表格操作MongoDB數(shù)據(jù)
在上一篇MongoDB學(xué)習(xí)筆記 中筆者帶領(lǐng)我們學(xué)習(xí)了如何通過(guò)samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作,本篇中筆者帶領(lǐng)我們學(xué)習(xí)在MVC模式下通過(guò)Jqgrid表格操作MongoDB數(shù)據(jù)。
看到下圖,是通過(guò)Jqgrid實(shí)現(xiàn)表格數(shù)據(jù)的基本增刪查改的操作。表格數(shù)據(jù)增刪改是一般企業(yè)應(yīng)用系統(tǒng)開(kāi)發(fā)的常見(jiàn)功能,不過(guò)不同的是這個(gè)表格數(shù)據(jù)來(lái)源是非關(guān)系型的數(shù)據(jù)庫(kù)MongoDB。nosql雖然概念新穎,但是MongoDB基本應(yīng)用實(shí)現(xiàn)起來(lái)還是比較輕松的,甚至代碼比基本的ADO.net訪問(wèn)關(guān)系數(shù)據(jù)源還要簡(jiǎn)潔。由于其本身的“非關(guān)系”的數(shù)據(jù)存儲(chǔ)方式,使得對(duì)象關(guān)系映射這個(gè)環(huán)節(jié)對(duì)于MongoDB來(lái)講顯得毫無(wú)意義,因此我們也不會(huì)對(duì)MongoDB引入所謂的“ORM”框架。

下面我們將逐步講解怎么在MVC模式下將MongoDB數(shù)據(jù)讀取,并展示在前臺(tái)Jqgrid表格上。這個(gè)“簡(jiǎn)易系統(tǒng)”的基本設(shè)計(jì)思想是這樣的:我們?cè)谝晥D層展示表格,Jqgrid相關(guān)Js邏輯全部放在一個(gè)Js文件中,控制層實(shí)現(xiàn)了“增刪查改”四個(gè)業(yè)務(wù),MongoDB的基本數(shù)據(jù)訪問(wèn)放在了模型層實(shí)現(xiàn)。下面我們一步步實(shí)現(xiàn)。
一、實(shí)現(xiàn)視圖層Jqgrid表格邏輯
首先,我們新建一個(gè)MVC空白項(xiàng)目,添加好jQuery、jQueryUI、Jqgrid的前端框架代碼:
然后在Views的Home文件夾下新建視圖“Index.aspx”,在視圖的body標(biāo)簽中添加如下HTML代碼:
- <div>
 - <table id="table1">
 - </table>
 - <div id="div1">
 - </div>
 - </div>
 
接著新建Scripts\Home文件夾,在該目錄新建“Index.js”文件,并再視圖中引用,代碼如下:
- jQuery(document).ready(function () {
 - //jqGrid初始化
 - jQuery("#table1").jqGrid({
 - url: '/Home/UserList',
 - datatype: 'json',
 - mtype: 'POST',
 - colNames: ['登錄名', '姓名', '年齡', '手機(jī)號(hào)', '郵箱地址', '操作'],
 - colModel: [
 - { name: 'UserId', index: 'UserId', width: 180, editable: true },
 - { name: 'UserName', index: 'UserName', width: 200, editable: true },
 - { name: 'Age', index: 'Age', width: 150, editable: true },
 - { name: 'Tel', index: 'Tel', width: 150, editable: true },
 - { name: 'Email', index: 'Email', width: 150, editable: true },
 - { name: 'Edit', index: 'Edit', width: 150, editable: false, align: 'center' }
 - ],
 - pager: '#div1',
 - postData: {},
 - rowNum: 5,
 - rowList: [5, 10, 20],
 - sortable: true,
 - caption: '用戶(hù)信息管理',
 - hidegrid: false,
 - rownumbers: true,
 - viewrecords: true
 - }).navGrid('#div1', { edit: false, add: false, del: false })
 - .navButtonAdd('#div1', {
 - caption: "編輯",
 - buttonicon: "ui-icon-add",
 - onClickButton: function () {
 - var id = $("#table1").getGridParam("selrow");
 - if (id == null) {
 - alert("請(qǐng)選擇行!");
 - return;
 - }
 - if (id == "newId") return;
 - $("#table1").editRow(id);
 - $("#table1").find("#" + id + "_UserId").attr("readonly","readOnly");
 - $("#table1").setCell(id, "Edit", "<input id='Button1' type='button' value='提交' onclick='Update(\"" + id + "\")' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"" + id + "\")' />");
 - }
 - }).navButtonAdd('#div1', {
 - caption: "刪除",
 - buttonicon: "ui-icon-del",
 - onClickButton: function () {
 - var id = $("#table1").getGridParam("selrow");
 - if (id == null) {
 - alert("請(qǐng)選擇行!");
 - return;
 - }
 - Delete(id);
 - }
 - }).navButtonAdd('#div1', {
 - caption: "新增",
 - buttonicon: "ui-icon-add",
 - onClickButton: function () {
 - $("#table1").addRowData("newId", -1);
 - $("#table1").editRow("newId");
 - $("#table1").setCell("newId", "Edit", "<input id='Button1' type='button' value='提交' onclick='Add()' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"newId\")' />");
 - }
 - });
 - });
 - //取消編輯狀態(tài)
 - function Cancel(id) {
 - if (id == "newId") $("#table1").delRowData("newId");
 - else $("#table1").restoreRow(id);
 - }
 - //向后臺(tái)ajax請(qǐng)求新增數(shù)據(jù)
 - function Add() {
 - var UserId = $("#table1").find("#newId" + "_UserId").val();
 - var UserName = $("#table1").find("#newId" + "_UserName").val();
 - var Age = $("#table1").find("#newId" + "_Age").val();
 - var Tel = $("#table1").find("#newId" + "_Tel").val();
 - var Email = $("#table1").find("#newId" + "_Email").val();
 - $.ajax({
 - type: "POST",
 - url: "/Home/Add",
 - data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,
 - success: function (msg) {
 - alert("新增數(shù)據(jù): " + msg);
 - $("#table1").trigger("reloadGrid");
 - }
 - });
 - }
 - //向后臺(tái)ajax請(qǐng)求更新數(shù)據(jù)
 - function Update(id) {
 - var UserId = $("#table1").find("#" + id + "_UserId").val();
 - var UserName = $("#table1").find("#" + id + "_UserName").val();
 - var Age = $("#table1").find("#" + id + "_Age").val();
 - var Tel = $("#table1").find("#" + id + "_Tel").val();
 - var Email = $("#table1").find("#" + id + "_Email").val();
 - $.ajax({
 - type: "POST",
 - url: "/Home/Update",
 - data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,
 - success: function (msg) {
 - alert("修改數(shù)據(jù): " + msg);
 - $("#table1").trigger("reloadGrid");
 - }
 - });
 - }
 - //向后臺(tái)ajax請(qǐng)求刪除數(shù)據(jù)
 - function Delete(id) {
 - var UserId = $("#table1").getCell(id, "UserId");
 - $.ajax({
 - type: "POST",
 - url: "/Home/Delete",
 - data: "UserId=" + UserId,
 - success: function (msg) {
 - alert("刪除數(shù)據(jù): " + msg);
 - $("#table1").trigger("reloadGrid");
 - }
 - });
 - }
 
二、實(shí)現(xiàn)控制層業(yè)務(wù)
在Controllers目錄下新建控制器“HomeController.cs”,Index.js中產(chǎn)生了四個(gè)ajax請(qǐng)求,對(duì)應(yīng)控制層也有四個(gè)業(yè)務(wù)方法。HomeController代碼如下:
- public class HomeController : Controller
 - {
 - UserModel userModel = new UserModel();
 - public ActionResult Index()
 - {
 - return View();
 - }
 - /// <summary>
 - /// 獲取全部用戶(hù)列表,通過(guò)json將數(shù)據(jù)提供給jqGrid
 - /// </summary>
 - public JsonResult UserList(string sord, string sidx, string rows, string page)
 - {
 - var list = userModel.FindAll();
 - int i = 0;
 - var query = from u in list
 - select new
 - {
 - id = i++,
 - cell = new string[]{
 - u["UserId"].ToString(),
 - u["UserName"].ToString(),
 - u["Age"].ToString(),
 - u["Tel"].ToString(),
 - u["Email"].ToString(),
 - "-"
 - }
 - };
 - var data = new
 - {
 - total = query.Count() / Convert.ToInt32(rows) + 1,
 - page = Convert.ToInt32(page),
 - records = query.Count(),
 - rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows))
 - };
 - return Json(data, JsonRequestBehavior.AllowGet);
 - }
 - /// <summary>
 - /// 響應(yīng)Js的“Add”ajax請(qǐng)求,執(zhí)行添加用戶(hù)操作
 - /// </summary>
 - public ContentResult Add(string UserId, string UserName, int Age, string Tel, string Email)
 - {
 - Document doc = new Document();
 - doc["UserId"] = UserId;
 - doc["UserName"] = UserName;
 - doc["Age"] = Age;
 - doc["Tel"] = Tel;
 - doc["Email"] = Email;
 - try
 - {
 - userModel.Add(doc);
 - return Content("添加成功");
 - }
 - catch
 - {
 - return Content("添加失敗");
 - }
 - }
 - /// <summary>
 - /// 響應(yīng)Js的“Delete”ajax請(qǐng)求,執(zhí)行刪除用戶(hù)操作
 - /// </summary>
 - public ContentResult Delete(string UserId)
 - {
 - try
 - {
 - userModel.Delete(UserId);
 - return Content("刪除成功");
 - }
 - catch
 - {
 - return Content("刪除失敗");
 - }
 - }
 - /// <summary>
 - /// 響應(yīng)Js的“Update”ajax請(qǐng)求,執(zhí)行更新用戶(hù)操作
 - /// </summary>
 - public ContentResult Update(string UserId, string UserName, int Age, string Tel, string Email)
 - {
 - Document doc = new Document();
 - doc["UserId"] = UserId;
 - doc["UserName"] = UserName;
 - doc["Age"] = Age;
 - doc["Tel"] = Tel;
 - doc["Email"] = Email;
 - try
 - {
 - userModel.Update(doc);
 - return Content("修改成功");
 - }
 - catch
 - {
 - return Content("修改失敗");
 - }
 - }
 - }
 
三、實(shí)現(xiàn)模型層數(shù)據(jù)訪問(wèn)
***,我們?cè)贛odels新建一個(gè)Home文件夾,添加模型“UserModel.cs”,實(shí)現(xiàn)MongoDB數(shù)據(jù)庫(kù)訪問(wèn)代碼如下:
- public class UserModel
 - {
 - //鏈接字符串(此處三個(gè)字段值根據(jù)需要可為讀配置文件)
 - public string connectionString = "mongodb://localhost";
 - //數(shù)據(jù)庫(kù)名
 - public string databaseName = "myDatabase";
 - //集合名
 - public string collectionName = "userCollection";
 - private Mongo mongo;
 - private MongoDatabase mongoDatabase;
 - private MongoCollection<Document> mongoCollection;
 - public UserModel()
 - {
 - mongo = new Mongo(connectionString);
 - mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
 - mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
 - mongo.Connect();
 - }
 - ~UserModel()
 - {
 - mongo.Disconnect();
 - }
 - /// <summary>
 - /// 增加一條用戶(hù)記錄
 - /// </summary>
 - /// <param name="doc"></param>
 - public void Add(Document doc)
 - {
 - mongoCollection.Insert(doc);
 - }
 - /// <summary>
 - /// 刪除一條用戶(hù)記錄
 - /// </summary>
 - public void Delete(string UserId)
 - {
 - mongoCollection.Remove(new Document { { "UserId", UserId } });
 - }
 - /// <summary>
 - /// 更新一條用戶(hù)記錄
 - /// </summary>
 - /// <param name="doc"></param>
 - public void Update(Document doc)
 - {
 - mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } });
 - }
 - /// <summary>
 - /// 查找所有用戶(hù)記錄
 - /// </summary>
 - /// <returns></returns>
 - public IEnumerable<Document> FindAll()
 - {
 - return mongoCollection.FindAll().Documents;
 - }
 - }
 
 
四、小結(jié)
  代碼下載:http://files.cnblogs.com/lipan/MongoDB_003.rar
自此為止一個(gè)簡(jiǎn)單MongoDB表格數(shù)據(jù)操作的功能就實(shí)現(xiàn)完畢了,相信讀者在看完這篇文章后,差不多都可以輕松實(shí)現(xiàn)MongoDB項(xiàng)目的開(kāi)發(fā)應(yīng)用了。聰明的你一定會(huì)比本文做的功能更完善,更好。下篇計(jì)劃講解linq的方式訪問(wèn)數(shù)據(jù)集合。
原文出處:http://www.cnblogs.com/lipan/archive/2011/03/11/1980227.html
【編輯推薦】
- MongoDB學(xué)習(xí)筆記(一) MongoDB介紹及安裝
 - MongoDB學(xué)習(xí)筆記(二) 通過(guò)samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作
 - 拋棄關(guān)系數(shù)據(jù)庫(kù) PHP程序員應(yīng)了解MongoDB的五件事
 - MongoDB,無(wú)模式文檔型數(shù)據(jù)庫(kù)簡(jiǎn)介
 - Visual Studio 2010下編譯調(diào)試MongoDB源碼
 















 
 
 




 
 
 
 