自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

MongoDB學(xué)習(xí)筆記(三) 在MVC模式下通過Jqgrid表格操作MongoDB數(shù)據(jù)

數(shù)據(jù)庫 其他數(shù)據(jù)庫 MongoDB
在上一篇MongoDB學(xué)習(xí)筆記 中筆者帶領(lǐng)我們學(xué)習(xí)了如何通過samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作,本篇中筆者帶領(lǐng)我們學(xué)習(xí)在MVC模式下通過Jqgrid表格操作MongoDB數(shù)據(jù)。

在上一篇MongoDB學(xué)習(xí)筆記 中筆者帶領(lǐng)我們學(xué)習(xí)了如何通過samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作,本篇中筆者帶領(lǐng)我們學(xué)習(xí)在MVC模式下通過Jqgrid表格操作MongoDB數(shù)據(jù)。

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

下面我們將逐步講解怎么在MVC模式下將MongoDB數(shù)據(jù)讀取,并展示在前臺Jqgrid表格上。這個(gè)“簡易系統(tǒng)”的基本設(shè)計(jì)思想是這樣的:我們在視圖層展示表格,Jqgrid相關(guān)Js邏輯全部放在一個(gè)Js文件中,控制層實(shí)現(xiàn)了“增刪查改”四個(gè)業(yè)務(wù),MongoDB的基本數(shù)據(jù)訪問放在了模型層實(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代碼:

  1. <div>    
  2.  
  3.     <table id="table1">    
  4.  
  5.     </table>    
  6.  
  7.     <div id="div1">    
  8.  
  9.     </div>    
  10.  
  11. </div>   

接著新建Scripts\Home文件夾,在該目錄新建“Index.js”文件,并再視圖中引用,代碼如下:

  1. jQuery(document).ready(function () {    
  2.     //jqGrid初始化    
  3.     jQuery("#table1").jqGrid({    
  4.         url: '/Home/UserList',    
  5.         datatype: 'json',    
  6.         mtype: 'POST',    
  7.         colNames: ['登錄名''姓名''年齡''手機(jī)號''郵箱地址''操作'],    
  8.         colModel: [    
  9.              { name'UserId'index'UserId', width: 180, editable: true },    
  10.              { name'UserName'index'UserName', width: 200, editable: true },    
  11.              { name'Age'index'Age', width: 150, editable: true },    
  12.              { name'Tel'index'Tel', width: 150, editable: true },    
  13.              { name'Email'index'Email', width: 150, editable: true },    
  14.              { name'Edit'index'Edit', width: 150, editable: false, align: 'center' }    
  15.              ],    
  16.         pager: '#div1',    
  17.         postData: {},    
  18.         rowNum: 5,    
  19.         rowList: [5, 10, 20],    
  20.         sortable: true,    
  21.         caption: '用戶信息管理',    
  22.         hidegrid: false,    
  23.         rownumbers: true,    
  24.         viewrecords: true   
  25.     }).navGrid('#div1', { edit: falseaddfalse, del: false })    
  26.             .navButtonAdd('#div1', {    
  27.                 caption: "編輯",    
  28.                 buttonicon: "ui-icon-add",    
  29.                 onClickButton: function () {    
  30.                     var id = $("#table1").getGridParam("selrow");    
  31.                     if (id == null) {    
  32.                         alert("請選擇行!");    
  33.                         return;    
  34.                     }    
  35.                     if (id == "newId"return;    
  36.                     $("#table1").editRow(id);    
  37.                     $("#table1").find("#" + id + "_UserId").attr("readonly","readOnly");    
  38.                     $("#table1").setCell(id, "Edit""<input id='Button1' type='button' value='提交' onclick='Update(\"" + id + "\")' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"" + id + "\")' />");    
  39.                 }    
  40.             }).navButtonAdd('#div1', {    
  41.                 caption: "刪除",    
  42.                 buttonicon: "ui-icon-del",    
  43.                 onClickButton: function () {    
  44.                     var id = $("#table1").getGridParam("selrow");    
  45.                     if (id == null) {    
  46.                         alert("請選擇行!");    
  47.                         return;    
  48.                     }    
  49.                     Delete(id);    
  50.                 }    
  51.             }).navButtonAdd('#div1', {    
  52.                 caption: "新增",    
  53.                 buttonicon: "ui-icon-add",    
  54.                 onClickButton: function () {    
  55.                     $("#table1").addRowData("newId", -1);    
  56.                     $("#table1").editRow("newId");    
  57.                     $("#table1").setCell("newId""Edit""<input id='Button1' type='button' value='提交' onclick='Add()' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"newId\")' />");    
  58.                 }    
  59.             });    
  60. });    
  61. //取消編輯狀態(tài)    
  62. function Cancel(id) {    
  63.     if (id == "newId") $("#table1").delRowData("newId");    
  64.     else $("#table1").restoreRow(id);    
  65. }    
  66. //向后臺ajax請求新增數(shù)據(jù)    
  67. function Add() {    
  68.     var UserId = $("#table1").find("#newId" + "_UserId").val();    
  69.     var UserName = $("#table1").find("#newId" + "_UserName").val();    
  70.     var Age = $("#table1").find("#newId" + "_Age").val();    
  71.     var Tel = $("#table1").find("#newId" + "_Tel").val();    
  72.     var Email = $("#table1").find("#newId" + "_Email").val();    
  73.     $.ajax({    
  74.         type: "POST",    
  75.         url: "/Home/Add",    
  76.         data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,    
  77.         success: function (msg) {    
  78.             alert("新增數(shù)據(jù): " + msg);    
  79.             $("#table1").trigger("reloadGrid");    
  80.         }    
  81.     });    
  82. }    
  83. //向后臺ajax請求更新數(shù)據(jù)    
  84. function Update(id) {    
  85.     var UserId = $("#table1").find("#" + id + "_UserId").val();    
  86.     var UserName = $("#table1").find("#" + id + "_UserName").val();    
  87.     var Age = $("#table1").find("#" + id + "_Age").val();    
  88.     var Tel = $("#table1").find("#" + id + "_Tel").val();    
  89.     var Email = $("#table1").find("#" + id + "_Email").val();    
  90.     $.ajax({    
  91.         type: "POST",    
  92.         url: "/Home/Update",    
  93.         data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,    
  94.         success: function (msg) {    
  95.             alert("修改數(shù)據(jù): " + msg);    
  96.             $("#table1").trigger("reloadGrid");    
  97.         }    
  98.     });    
  99. }    
  100. //向后臺ajax請求刪除數(shù)據(jù)    
  101. function Delete(id) {    
  102.     var UserId = $("#table1").getCell(id, "UserId");    
  103.     $.ajax({    
  104.         type: "POST",    
  105.         url: "/Home/Delete",    
  106.         data: "UserId=" + UserId,    
  107.         success: function (msg) {    
  108.             alert("刪除數(shù)據(jù): " + msg);    
  109.             $("#table1").trigger("reloadGrid");    
  110.         }    
  111.     });    
  112. }  

二、實(shí)現(xiàn)控制層業(yè)務(wù)

  在Controllers目錄下新建控制器“HomeController.cs”,Index.js中產(chǎn)生了四個(gè)ajax請求,對應(yīng)控制層也有四個(gè)業(yè)務(wù)方法。HomeController代碼如下:

  1. public class HomeController : Controller    
  2. {    
  3.     UserModel userModel = new UserModel();    
  4.     public ActionResult Index()    
  5.     {    
  6.         return View();    
  7.     }    
  8.     /// <summary>    
  9.     /// 獲取全部用戶列表,通過json將數(shù)據(jù)提供給jqGrid    
  10.     /// </summary>    
  11.     public JsonResult UserList(string sord, string sidx, string rows, string page)    
  12.     {    
  13.         var list = userModel.FindAll();    
  14.         int i = 0;    
  15.         var query = from u in list    
  16.                     select new   
  17.                     {    
  18.                         id = i++,    
  19.                         cell = new string[]{    
  20.                             u["UserId"].ToString(),    
  21.                             u["UserName"].ToString(),    
  22.                             u["Age"].ToString(),    
  23.                             u["Tel"].ToString(),    
  24.                             u["Email"].ToString(),    
  25.                             "-"   
  26.                         }    
  27.                     };    
  28.         var data = new   
  29.         {    
  30.             total = query.Count() / Convert.ToInt32(rows) + 1,    
  31.             page = Convert.ToInt32(page),    
  32.             records = query.Count(),    
  33.             rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows))    
  34.         };    
  35.         return Json(data, JsonRequestBehavior.AllowGet);    
  36.     }    
  37.     /// <summary>    
  38.     /// 響應(yīng)Js的“Add”ajax請求,執(zhí)行添加用戶操作    
  39.     /// </summary>    
  40.     public ContentResult Add(string UserId, string UserName, int Age, string Tel, string Email)    
  41.     {    
  42.         Document doc = new Document();    
  43.         doc["UserId"] = UserId;    
  44.         doc["UserName"] = UserName;    
  45.         doc["Age"] = Age;    
  46.         doc["Tel"] = Tel;    
  47.         doc["Email"] = Email;    
  48.         try   
  49.         {    
  50.             userModel.Add(doc);    
  51.             return Content("添加成功");    
  52.  
  53.         }    
  54.         catch   
  55.         {    
  56.             return Content("添加失敗");    
  57.         }    
  58.     }    
  59.     /// <summary>    
  60.     /// 響應(yīng)Js的“Delete”ajax請求,執(zhí)行刪除用戶操作    
  61.     /// </summary>    
  62.     public ContentResult Delete(string UserId)    
  63.     {    
  64.         try   
  65.         {    
  66.             userModel.Delete(UserId);    
  67.             return Content("刪除成功");    
  68.         }    
  69.         catch   
  70.         {    
  71.             return Content("刪除失敗");    
  72.         }    
  73.     }    
  74.     
  75.     /// <summary>    
  76.     /// 響應(yīng)Js的“Update”ajax請求,執(zhí)行更新用戶操作    
  77.     /// </summary>    
  78.     public ContentResult Update(string UserId, string UserName, int Age, string Tel, string Email)    
  79.     {    
  80.         Document doc = new Document();    
  81.         doc["UserId"] = UserId;    
  82.         doc["UserName"] = UserName;    
  83.         doc["Age"] = Age;    
  84.         doc["Tel"] = Tel;    
  85.         doc["Email"] = Email;    
  86.         try   
  87.         {    
  88.             userModel.Update(doc);    
  89.             return Content("修改成功");    
  90.         }    
  91.         catch   
  92.         {    
  93.             return Content("修改失敗");    
  94.         }    
  95.     }    
  96. }  

三、實(shí)現(xiàn)模型層數(shù)據(jù)訪問

  ***,我們在Models新建一個(gè)Home文件夾,添加模型“UserModel.cs”,實(shí)現(xiàn)MongoDB數(shù)據(jù)庫訪問代碼如下:

  1. public class UserModel    
  2.  {    
  3.      //鏈接字符串(此處三個(gè)字段值根據(jù)需要可為讀配置文件)    
  4.      public string connectionString = "mongodb://localhost";    
  5.      //數(shù)據(jù)庫名    
  6.      public string databaseName = "myDatabase";    
  7.      //集合名     
  8.      public string collectionName = "userCollection";    
  9.      private Mongo mongo;    
  10.      private MongoDatabase mongoDatabase;    
  11.      private MongoCollection<Document> mongoCollection;    
  12.      public UserModel()    
  13.      {    
  14.          mongo = new Mongo(connectionString);    
  15.          mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;    
  16.          mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;    
  17.          mongo.Connect();    
  18.      }    
  19.      ~UserModel()    
  20.      {    
  21.          mongo.Disconnect();    
  22.      }    
  23.      /// <summary>    
  24.      /// 增加一條用戶記錄    
  25.      /// </summary>    
  26.      /// <param name="doc"></param>    
  27.      public void Add(Document doc)    
  28.      {    
  29.          mongoCollection.Insert(doc);    
  30.      }    
  31.      /// <summary>    
  32.      /// 刪除一條用戶記錄    
  33.      /// </summary>    
  34.      public void Delete(string UserId)    
  35.      {    
  36.          mongoCollection.Remove(new Document { { "UserId", UserId } });    
  37.      }    
  38.      /// <summary>    
  39.      /// 更新一條用戶記錄    
  40.      /// </summary>    
  41.      /// <param name="doc"></param>    
  42.      public void Update(Document doc)    
  43.      {    
  44.          mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } });    
  45.      }    
  46.      /// <summary>    
  47.      /// 查找所有用戶記錄    
  48.      /// </summary>    
  49.      /// <returns></returns>    
  50.      public IEnumerable<Document> FindAll()    
  51.      {    
  52.          return mongoCollection.FindAll().Documents;    
  53.      }    
  54.  } 

 
四、小結(jié)
  代碼下載:http://files.cnblogs.com/lipan/MongoDB_003.rar

  自此為止一個(gè)簡單MongoDB表格數(shù)據(jù)操作的功能就實(shí)現(xiàn)完畢了,相信讀者在看完這篇文章后,差不多都可以輕松實(shí)現(xiàn)MongoDB項(xiàng)目的開發(fā)應(yīng)用了。聰明的你一定會(huì)比本文做的功能更完善,更好。下篇計(jì)劃講解linq的方式訪問數(shù)據(jù)集合。

原文出處:http://www.cnblogs.com/lipan/archive/2011/03/11/1980227.html

 

【編輯推薦】

  1. MongoDB學(xué)習(xí)筆記(一) MongoDB介紹及安裝
  2. MongoDB學(xué)習(xí)筆記(二) 通過samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作
  3. 拋棄關(guān)系數(shù)據(jù)庫 PHP程序員應(yīng)了解MongoDB的五件事
  4. MongoDB,無模式文檔型數(shù)據(jù)庫簡介
  5. Visual Studio 2010下編譯調(diào)試MongoDB源碼

 

責(zé)任編輯:艾婧 來源: 博客園
相關(guān)推薦

2011-03-21 13:28:14

MongoDB文件存取

2011-03-09 09:18:49

MongoDBsamus

2011-09-14 15:30:00

MongoDB

2011-03-08 10:27:25

MongoDB介紹安裝

2011-03-17 09:06:34

MongoDB文檔結(jié)構(gòu)

2011-06-30 13:31:35

MongoDB

2011-03-28 13:29:22

MongoDB索引用法效率分析

2012-07-16 10:19:02

MongoDB

2012-08-17 09:48:55

MongoDB

2023-12-18 16:07:15

2011-01-10 11:09:16

linuxMongoDB安裝

2022-03-10 09:08:43

數(shù)據(jù)庫Mongodb數(shù)據(jù)庫轉(zhuǎn)

2017-07-07 10:55:14

數(shù)據(jù)庫MongoDB設(shè)計(jì)模式

2021-08-04 09:00:53

Python數(shù)據(jù)庫Python基礎(chǔ)

2013-11-28 09:48:55

MongoDBSharding分片

2021-03-04 10:37:37

PythonMongoDB數(shù)據(jù)庫

2011-06-03 10:06:57

MongoDB

2009-09-04 09:33:50

MongoDB

2013-11-22 10:02:59

Mongodb千萬級數(shù)據(jù)python

2017-09-08 14:30:33

MongoDB安裝操作命令
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號