在MVC模式下通过Jqgrid表格操作MongoDB数据

导语 看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作。表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB。nosql虽然概念新颖,但是MongoDB基本应用
看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作。表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB。nosql虽然概念新颖,但是MongoDB基本应用实现起来还是比较轻松的,甚至代码比基本的ADO.net访问关系数据源还要简洁。由于其本身的“非关系”的数据存储方式,使得对象关系映射这个环节对于MongoDB来讲显得毫无意义,因此我们也不会对MongoDB引入所谓的“ORM”框架。

  博学谷

  下面我们将逐步讲解怎么在MVC模式下将MongoDB数据读取,并展示在前台Jqgrid表格上。这个“简易系统”的基本设计思想是这样的:我们在视图层展示表格,Jqgrid相关Js逻辑全部放在一个Js文件中,控制层实现了“增删查改”四个业务,MongoDB的基本数据访问放在了模型层实现。下面我们一步步实现。
 

一、实现视图层Jqgrid表格逻辑

  首先,我们新建一个MVC空白项目,添加好jQuery、jQueryUI、Jqgrid的BETWAY登录框架代码:

  然后在Views的Home文件夹下新建视图“Index.aspx”,在视图的body标签中添加如下HTML代码:

 
  1. <div> 
  2.     <table id="table1"
  3.     </table> 
  4.     <div id="div1"
  5.     </div> 
  6. </div> 

  接着新建Scripts\Home文件夹,在该目录新建“Index.js”文件,并再视图中引用,代码如下:

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

 

二、实现控制层业务

  在Controllers目录下新建控制器“HomeController.cs”,Index.js中产生了四个ajax请求,对应控制层也有四个业务方法。HomeController代码如下:
 

  1. public class HomeController : Controller 
  2.     UserModel userModel = new UserModel(); 
  3.     public ActionResult Index() 
  4.     { 
  5.         return View(); 
  6.     } 
  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.   
  29.         var data = new 
  30.         { 
  31.             total = query.Count() / Convert.ToInt32(rows) + 1, 
  32.             page = Convert.ToInt32(page), 
  33.             records = query.Count(), 
  34.             rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows)) 
  35.         }; 
  36.   
  37.         return Json(data, JsonRequestBehavior.AllowGet); 
  38.     } 
  39.   
  40.     /// <summary> 
  41.     /// 响应Js的“Add”ajax请求,执行添加用户操作 
  42.     /// </summary> 
  43.     public ContentResult Add(string UserId, string UserName, int Age, string Tel, string Email) 
  44.     { 
  45.         Document doc = new Document(); 
  46.         doc["UserId"] = UserId; 
  47.         doc["UserName"] = UserName; 
  48.         doc["Age"] = Age; 
  49.         doc["Tel"] = Tel; 
  50.         doc["Email"] = Email; 
  51.   
  52.         try 
  53.         { 
  54.             userModel.Add(doc); 
  55.             return Content("添加成功"); 
  56.         } 
  57.         catch 
  58.         { 
  59.             return Content("添加失败"); 
  60.         } 
  61.     } 
  62.   
  63.     /// <summary> 
  64.     /// 响应Js的“Delete”ajax请求,执行删除用户操作 
  65.     /// </summary> 
  66.     public ContentResult Delete(string UserId) 
  67.     { 
  68.         try 
  69.         { 
  70.             userModel.Delete(UserId); 
  71.             return Content("删除成功"); 
  72.         } 
  73.         catch 
  74.         { 
  75.             return Content("删除失败"); 
  76.         } 
  77.     } 
  78.   
  79.     /// <summary> 
  80.     /// 响应Js的“Update”ajax请求,执行更新用户操作 
  81.     /// </summary> 
  82.     public ContentResult Update(string UserId, string UserName, int Age, string Tel, string Email) 
  83.     { 
  84.         Document doc = new Document(); 
  85.         doc["UserId"] = UserId; 
  86.         doc["UserName"] = UserName; 
  87.         doc["Age"] = Age; 
  88.         doc["Tel"] = Tel; 
  89.         doc["Email"] = Email; 
  90.         try 
  91.         { 
  92.             userModel.Update(doc); 
  93.             return Content("修改成功"); 
  94.         } 
  95.         catch 
  96.         { 
  97.             return Content("修改失败"); 
  98.         } 
  99.     } 

三、实现模型层数据访问

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

  1. public class UserModel 
  2.     //链接字符串(此处三个字段值根据需要可为读配置文件) 
  3.     public string connectionString = "mongodb://localhost"
  4.     //数据库名 
  5.     public string databaseName = "myDatabase"
  6.     //集合名 
  7.     public string collectionName = "userCollection"
  8.   
  9.     private Mongo mongo; 
  10.     private MongoDatabase mongoDatabase; 
  11.     private MongoCollection<Document> mongoCollection; 
  12.   
  13.     public UserModel() 
  14.     { 
  15.         mongo = new Mongo(connectionString); 
  16.         mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; 
  17.         mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; 
  18.         mongo.Connect(); 
  19.     } 
  20.     ~UserModel() 
  21.     { 
  22.         mongo.Disconnect(); 
  23.     } 
  24.   
  25.     /// <summary> 
  26.     /// 增加一条用户记录 
  27.     /// </summary> 
  28.     /// <param name="doc"></param> 
  29.     public void Add(Document doc) 
  30.     { 
  31.         mongoCollection.Insert(doc); 
  32.     } 
  33.   
  34.     /// <summary> 
  35.     /// 删除一条用户记录 
  36.     /// </summary> 
  37.     public void Delete(string UserId) 
  38.     { 
  39.         mongoCollection.Remove(new Document { { "UserId", UserId } }); 
  40.     } 
  41.   
  42.     /// <summary> 
  43.     /// 更新一条用户记录 
  44.     /// </summary> 
  45.     /// <param name="doc"></param> 
  46.     public void Update(Document doc) 
  47.     { 
  48.         mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } }); 
  49.     } 
  50.   
  51.     /// <summary> 
  52.     /// 查找所有用户记录 
  53.     /// </summary> 
  54.     /// <returns></returns> 
  55.     public IEnumerable<Document> FindAll() 
  56.     { 
  57.         return mongoCollection.FindAll().Documents; 
  58.     } 
  59.   

代码下载:mongodb_003.rar
 

https://www.nucmc.com/ true 在MVC模式下通过Jqgrid表格操作MongoDB数据 https://www.nucmc.com/show-72-549-1.html report 24571.5 看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作。表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB。nosql虽然概念新颖,但是MongoDB基本应用
TAG:mvc mongodb Jqgrid
本站欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果
转载请注明: 文章转载自:BETWAY官网网 https://www.nucmc.com/show-72-549-1.html
BETWAY官网网 Copyright 2012-2014 www.nucmc.com All rights reserved.(晋ICP备13001436号-1)