MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
创始人
2024-07-22 20:41:22
0

在上一篇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.     
  2.  
  3.         
  4.  
  5.         
  6.  
  7.         
  8.  
  9.     
    
  •  
  •    

    接着新建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: false, add: false, 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", "");    
    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", "");    
    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.     ///     
    9.     /// 获取全部用户列表,通过json将数据提供给jqGrid    
    10.     ///     
    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.     ///     
    38.     /// 响应Js的“Add”ajax请求,执行添加用户操作    
    39.     ///     
    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.     ///     
    60.     /// 响应Js的“Delete”ajax请求,执行删除用户操作    
    61.     ///     
    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.     ///     
    76.     /// 响应Js的“Update”ajax请求,执行更新用户操作    
    77.     ///     
    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 mongoCollection;    
    12.      public UserModel()    
    13.      {    
    14.          mongo = new Mongo(connectionString);    
    15.          mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;    
    16.          mongoCollection = mongoDatabase.GetCollection(collectionName) as MongoCollection;    
    17.          mongo.Connect();    
    18.      }    
    19.      ~UserModel()    
    20.      {    
    21.          mongo.Disconnect();    
    22.      }    
    23.      ///     
    24.      /// 增加一条用户记录    
    25.      ///     
    26.      ///     
    27.      public void Add(Document doc)    
    28.      {    
    29.          mongoCollection.Insert(doc);    
    30.      }    
    31.      ///     
    32.      /// 删除一条用户记录    
    33.      ///     
    34.      public void Delete(string UserId)    
    35.      {    
    36.          mongoCollection.Remove(new Document { { "UserId", UserId } });    
    37.      }    
    38.      ///     
    39.      /// 更新一条用户记录    
    40.      ///     
    41.      ///     
    42.      public void Update(Document doc)    
    43.      {    
    44.          mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } });    
    45.      }    
    46.      ///     
    47.      /// 查找所有用户记录    
    48.      ///     
    49.      ///     
    50.      public IEnumerable 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源码

     

    相关内容

    热门资讯

    如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
    如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
    施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
    20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
    德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
    为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
    《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
    2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...