MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据

数据库 其他数据库 MongoDB
在上一篇MongoDB学习笔记 中笔者带领我们学习了如何通过samus驱动实现基本数据操作,本篇中笔者带领我们学习在MVC模式下通过Jqgrid表格操作MongoDB数据。

在上一篇MongoDB学习笔记 中笔者带领我们学习了如何通过samus驱动实现基本数据操作,本篇中笔者带领我们学习在MVC模式下通过Jqgrid表格操作MongoDB数据。

看到下图,是通过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代码:

  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: ['登录名''姓名''年龄''手机号''邮箱地址''操作'],    
  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. //取消编辑状态    
  62. function Cancel(id) {    
  63.     if (id == "newId") $("#table1").delRowData("newId");    
  64.     else $("#table1").restoreRow(id);    
  65. }    
  66. //向后台ajax请求新增数据    
  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("新增数据: " + msg);    
  79.             $("#table1").trigger("reloadGrid");    
  80.         }    
  81.     });    
  82. }    
  83. //向后台ajax请求更新数据    
  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("修改数据: " + msg);    
  96.             $("#table1").trigger("reloadGrid");    
  97.         }    
  98.     });    
  99. }    
  100. //向后台ajax请求删除数据    
  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("删除数据: " + msg);    
  109.             $("#table1").trigger("reloadGrid");    
  110.         }    
  111.     });    
  112. }  

二、实现控制层业务

  在Controllers目录下新建控制器“HomeController.cs”,Index.js中产生了四个ajax请求,对应控制层也有四个业务方法。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将数据提供给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.     /// 响应Js的“Add”ajax请求,执行添加用户操作    
  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.     /// 响应Js的“Delete”ajax请求,执行删除用户操作    
  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.     /// 响应Js的“Update”ajax请求,执行更新用户操作    
  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. }  

三、实现模型层数据访问

  ***,我们在Models新建一个Home文件夹,添加模型“UserModel.cs”,实现MongoDB数据库访问代码如下:

  1. public class UserModel    
  2.  {    
  3.      //链接字符串(此处三个字段值根据需要可为读配置文件)    
  4.      public string connectionString = "mongodb://localhost";    
  5.      //数据库名    
  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.  } 

 
四、小结
  代码下载:http://files.cnblogs.com/lipan/MongoDB_003.rar

  自此为止一个简单MongoDB表格数据操作的功能就实现完毕了,相信读者在看完这篇文章后,差不多都可以轻松实现MongoDB项目的开发应用了。聪明的你一定会比本文做的功能更完善,更好。下篇计划讲解linq的方式访问数据集合。

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

 

【编辑推荐】

  1. MongoDB学习笔记(一) MongoDB介绍及安装
  2. MongoDB学习笔记(二) 通过samus驱动实现基本数据操作
  3. 抛弃关系数据库 PHP程序员应了解MongoDB的五件事
  4. MongoDB,无模式文档型数据库简介
  5. Visual Studio 2010下编译调试MongoDB源码

 

责任编辑:艾婧 来源: 博客园
相关推荐

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文档结构

2011-06-30 13:31:35

MongoDB

2011-03-28 13:29:22

MongoDB索引用法效率分析

2012-08-17 09:48:55

MongoDB

2012-07-16 10:19:02

MongoDB

2023-12-18 16:07:15

2022-03-10 09:08:43

数据库Mongodb数据库转

2011-01-10 11:09:16

linuxMongoDB安装

2017-07-07 10:55:14

数据库MongoDB设计模式

2021-08-04 09:00:53

Python数据库Python基础

2013-11-28 09:48:55

MongoDBSharding分片

2009-09-04 09:33:50

MongoDB

2021-03-04 10:37:37

PythonMongoDB数据库

2011-06-03 10:06:57

MongoDB

2013-11-22 10:02:59

Mongodb千万级数据python

2023-03-09 11:16:57

MongoDB数据节点
点赞
收藏

51CTO技术栈公众号