Chinaunix首页 | 论坛 | 博客
  • 博客访问: 58075
  • 博文数量: 20
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 282
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-20 17:23
个人简介

我的博客园;http://www.cnblogs.com/geekpaul/

文章分类

全部博文(20)

文章存档

2015年(7)

2014年(13)

我的朋友

分类: NOSQL

2015-01-30 17:04:53

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

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

    首先,我们新建一个MVC空白项目,添加好jQueryjQueryUIJqgrid的前端框架代码,

然后在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", "");
  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", "");
  59.                 }
  60.             });
  61. });
  62.  
  63. //取消编辑状态
  64. function Cancel(id) {
  65.     if (id == "newId") $("#table1").delRowData("newId");
  66.     else $("#table1").restoreRow(id);
  67. }
  68.  
  69. //向后台ajax请求新增数据
  70. function Add() {
  71.     var UserId = $("#table1").find("#newId" + "_UserId").val();
  72.     var UserName = $("#table1").find("#newId" + "_UserName").val();
  73.     var Age = $("#table1").find("#newId" + "_Age").val();
  74.     var Tel = $("#table1").find("#newId" + "_Tel").val();
  75.     var Email = $("#table1").find("#newId" + "_Email").val();
  76.  
  77.     $.ajax({
  78.         type: "POST",
  79.         url: "/Home/Add",
  80.         data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,
  81.         success: function (msg) {
  82.             alert("新增数据: " + msg);
  83.             $("#table1").trigger("reloadGrid");
  84.         }
  85.     });
  86. }
  87.  
  88. //向后台ajax请求更新数据
  89. function Update(id) {
  90.     var UserId = $("#table1").find("#" + id + "_UserId").val();
  91.     var UserName = $("#table1").find("#" + id + "_UserName").val();
  92.     var Age = $("#table1").find("#" + id + "_Age").val();
  93.     var Tel = $("#table1").find("#" + id + "_Tel").val();
  94.     var Email = $("#table1").find("#" + id + "_Email").val();
  95.  
  96.     $.ajax({
  97.         type: "POST",
  98.         url: "/Home/Update",
  99.         data: "UserId=" + UserId + "&UserName=" + UserName + "&Age=" + Age + "&Tel=" + Tel + "&Email=" + Email,
  100.         success: function (msg) {
  101.             alert("修改数据: " + msg);
  102.             $("#table1").trigger("reloadGrid");
  103.         }
  104.     });
  105. }
  106.  
  107. //向后台ajax请求删除数据
  108. function Delete(id) {
  109.     var UserId = $("#table1").getCell(id, "UserId");
  110.     $.ajax({
  111.         type: "POST",
  112.         url: "/Home/Delete",
  113.         data: "UserId=" + UserId,
  114.         success: function (msg) {
  115.             alert("删除数据: " + msg);
  116.             $("#table1").trigger("reloadGrid");
  117.         }
  118.     });
  119. }
2. 实现控制层业务

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.     ///
  10.     /// 获取全部用户列表,通过json将数据提供给jqGrid
  11.     ///
  12.     public JsonResult UserList(string sord, string sidx, string rows, string page)
  13.     {
  14.         var list = userModel.FindAll();
  15.         int i = 0;
  16.         var query = from u in list
  17.                     select new
  18.                     {
  19.                         id = i++,
  20.                         cell = new string[]{
  21.                             u["UserId"].ToString(),
  22.                             u["UserName"].ToString(),
  23.                             u["Age"].ToString(),
  24.                             u["Tel"].ToString(),
  25.                             u["Email"].ToString(),
  26.                             "-"
  27.                         }
  28.                     };
  29.  
  30.         var data = new
  31.         {
  32.             total = query.Count() / Convert.ToInt32(rows) + 1,
  33.             page = Convert.ToInt32(page),
  34.             records = query.Count(),
  35.             rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows))
  36.         };
  37.  
  38.         return Json(data, JsonRequestBehavior.AllowGet);
  39.     }
  40.  
  41.     ///
  42.     /// 响应Js的“Add”ajax请求,执行添加用户操作
  43.     ///
  44.     public ContentResult Add(string UserId, string UserName, int Age, string Tel, string Email)
  45.     {
  46.         Document doc = new Document();
  47.         doc["UserId"] = UserId;
  48.         doc["UserName"] = UserName;
  49.         doc["Age"] = Age;
  50.         doc["Tel"] = Tel;
  51.         doc["Email"] = Email;
  52.  
  53.         try
  54.         {
  55.             userModel.Add(doc);
  56.             return Content("添加成功");
  57.         }
  58.         catch
  59.         {
  60.             return Content("添加失败");
  61.         }
  62.     }
  63.  
  64.     ///
  65.     /// 响应Js的“Delete”ajax请求,执行删除用户操作
  66.     ///
  67.     public ContentResult Delete(string UserId)
  68.     {
  69.         try
  70.         {
  71.             userModel.Delete(UserId);
  72.             return Content("删除成功");
  73.         }
  74.         catch
  75.         {
  76.             return Content("删除失败");
  77.         }
  78.     }
  79.  
  80.     ///
  81.     /// 响应Js的“Update”ajax请求,执行更新用户操作
  82.     ///
  83.     public ContentResult Update(string UserId, string UserName, int Age, string Tel, string Email)
  84.     {
  85.         Document doc = new Document();
  86.         doc["UserId"] = UserId;
  87.         doc["UserName"] = UserName;
  88.         doc["Age"] = Age;
  89.         doc["Tel"] = Tel;
  90.         doc["Email"] = Email;
  91.         try
  92.         {
  93.             userModel.Update(doc);
  94.             return Content("修改成功");
  95.         }
  96.         catch
  97.         {
  98.             return Content("修改失败");
  99.         }
  100.     }
  101. }
3. 实现模型层数据访问

最后,我们在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.  
  10.     private Mongo mongo;
  11.     private MongoDatabase mongoDatabase;
  12.     private MongoCollection<Document> mongoCollection;
  13.  
  14.     public UserModel()
  15.     {
  16.         mongo = new Mongo(connectionString);
  17.         mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
  18.         mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
  19.         mongo.Connect();
  20.     }
  21.     ~UserModel()
  22.     {
  23.         mongo.Disconnect();
  24.     }
  25.  
  26.     ///
  27.     /// 增加一条用户记录
  28.     ///
  29.     ///
  30.     public void Add(Document doc)
  31.     {
  32.         mongoCollection.Insert(doc);
  33.     }
  34.  
  35.     ///
  36.     /// 删除一条用户记录
  37.     ///
  38.     public void Delete(string UserId)
  39.     {
  40.         mongoCollection.Remove(new Document { { "UserId", UserId } });
  41.     }
  42.  
  43.     ///
  44.     /// 更新一条用户记录
  45.     ///
  46.     ///
  47.     public void Update(Document doc)
  48.     {
  49.         mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } });
  50.     }
  51.  
  52.     ///
  53.     /// 查找所有用户记录
  54.     ///
  55.     ///
  56.     public IEnumerable<Document> FindAll()
  57.     {
  58.         return mongoCollection.FindAll().Documents;
  59.     }
  60.  
  61. }



阅读(1075) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~