MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作。表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源是非关系型的数据库MongoDB。nosql虽然概念新颖,但是MongoDB基本应用实现起来还是比较轻松的,甚至代码比基本的ADO.net访问关系数据源还要简洁。由于其本身的“非关系”的数据存储方式,使得对象关系映射这个环节对于MongoDB来讲显得毫无意义,因此我们也不会对MongoDB引入所谓的“ORM”框架。
下面我们将逐步讲解怎么在MVC模式下将MongoDB数据读取,并展示在前台Jqgrid表格上。这个“简易系统”的基本设计思想是这样的:我们在视图层展示表格,Jqgrid相关Js逻辑全部放在一个Js文件中,控制层实现了“增删查改”四个业务,MongoDB的基本数据访问放在了模型层实现。下面我们一步步实现。
系列目录
MongoDB学习笔记(一) MongoDB介绍及安装MongoDB学习笔记(二) 通过samus驱动实现基本数据操作
MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据
MongoDB学习笔记(四) 用MongoDB的文档结构描述数据关系
MongoDB学习笔记(五) MongoDB文件存取操作
MongoDB学习笔记(六) MongoDB索引用法和效率分析
一、实现视图层Jqgrid表格逻辑
首先,我们新建一个MVC空白项目,添加好jQuery、jQueryUI、Jqgrid的前端框架代码:
然后在Views的Home文件夹下新建视图“Index.aspx”,在视图的body标签中添加如下HTML代码:
< div > < table id="table1"> </ table > < div id="div1"> </ div > </ div > |
接着新建Scripts\Home文件夹,在该目录新建“Index.js”文件,并再视图中引用,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | jQuery(document).ready( function () { //jqGrid初始化 jQuery( "#table1" ).jqGrid({ url: '/Home/UserList' , datatype: 'json' , mtype: 'POST' , colNames: [ '登录名' , '姓名' , '年龄' , '手机号' , '邮箱地址' , '操作' ], 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: '用户信息管理' , 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( "请选择行!" ); 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( "请选择行!" ); 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\")' />" ); } }); }); //取消编辑状态 function Cancel(id) { if (id == "newId" ) $( "#table1" ).delRowData( "newId" ); else $( "#table1" ).restoreRow(id); } //向后台ajax请求新增数据 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( "新增数据: " + msg); $( "#table1" ).trigger( "reloadGrid" ); } }); } //向后台ajax请求更新数据 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( "修改数据: " + msg); $( "#table1" ).trigger( "reloadGrid" ); } }); } //向后台ajax请求删除数据 function Delete(id) { var UserId = $( "#table1" ).getCell(id, "UserId" ); $.ajax({ type: "POST" , url: "/Home/Delete" , data: "UserId=" + UserId, success: function (msg) { alert( "删除数据: " + msg); $( "#table1" ).trigger( "reloadGrid" ); } }); } |
二、实现控制层业务
在Controllers目录下新建控制器“HomeController.cs”,Index.js中产生了四个ajax请求,对应控制层也有四个业务方法。HomeController代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | public class HomeController : Controller { UserModel userModel = new UserModel(); public ActionResult Index() { return View(); } /// <summary> /// 获取全部用户列表,通过json将数据提供给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> /// 响应Js的“Add”ajax请求,执行添加用户操作 /// </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> /// 响应Js的“Delete”ajax请求,执行删除用户操作 /// </summary> public ContentResult Delete( string UserId) { try { userModel.Delete(UserId); return Content( "删除成功" ); } catch { return Content( "删除失败" ); } } /// <summary> /// 响应Js的“Update”ajax请求,执行更新用户操作 /// </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( "修改失败" ); } } } |
三、实现模型层数据访问
最后,我们在Models新建一个Home文件夹,添加模型“UserModel.cs”,实现MongoDB数据库访问代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | public class UserModel { //链接字符串(此处三个字段值根据需要可为读配置文件) public string connectionString = "mongodb://localhost" ; //数据库名 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> /// 增加一条用户记录 /// </summary> /// <param name="doc"></param> public void Add(Document doc) { mongoCollection.Insert(doc); } /// <summary> /// 删除一条用户记录 /// </summary> public void Delete( string UserId) { mongoCollection.Remove( new Document { { "UserId" , UserId } }); } /// <summary> /// 更新一条用户记录 /// </summary> /// <param name="doc"></param> public void Update(Document doc) { mongoCollection.FindAndModify(doc, new Document { { "UserId" , doc[ "UserId" ].ToString() } }); } /// <summary> /// 查找所有用户记录 /// </summary> /// <returns></returns> public IEnumerable<Document> FindAll() { return mongoCollection.FindAll().Documents; } } |
四、小结
代码下载:https://files.cnblogs.com/lipan/MongoDB_003.rar
自此为止一个简单MongoDB表格数据操作的功能就实现完毕了,相信读者在看完这篇文章后,差不多都可以轻松实现MongoDB项目的开发应用了。聪明的你一定会比本文做的功能更完善,更好。下篇计划讲解linq的方式访问数据集合。
出处:[Lipan] (http://www.cnblogs.com/lipan/)
版权声明:本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix