发表于 2015-7-9 12:00:51

MongoDB学习笔记(三) 在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代码:





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




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




001public class HomeController : Controller
002{
003    UserModel userModel = new UserModel();
004    public ActionResult Index()
005    {
006      return View();
007    }
008
009    ///
010    /// 获取全部用户列表,通过json将数据提供给jqGrid
011    ///
012    public JsonResult UserList(string sord, string sidx, string rows, string page)
013    {
014      var list = userModel.FindAll();
015      int i = 0;
016      var query = from u in list
017                  select new
018                  {
019                        id = i++,
020                        cell = new string[]{
021                            u["UserId"].ToString(),
022                            u["UserName"].ToString(),
023                            u["Age"].ToString(),
024                            u["Tel"].ToString(),
025                            u["Email"].ToString(),
026                            "-"
027                        }
028                  };
029
030      var data = new
031      {
032            total = query.Count() / Convert.ToInt32(rows) + 1,
033            page = Convert.ToInt32(page),
034            records = query.Count(),
035            rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows))
036      };
037
038      return Json(data, JsonRequestBehavior.AllowGet);
039    }
040
041    ///
042    /// 响应Js的“Add”ajax请求,执行添加用户操作
043    ///
044    public ContentResult Add(string UserId, string UserName, int Age, string Tel, string Email)
045    {
046      Document doc = new Document();
047      doc["UserId"] = UserId;
048      doc["UserName"] = UserName;
049      doc["Age"] = Age;
050      doc["Tel"] = Tel;
051      doc["Email"] = Email;
052
053      try
054      {
055            userModel.Add(doc);
056            return Content("添加成功");
057      }
058      catch
059      {
060            return Content("添加失败");
061      }
062    }
063
064    ///
065    /// 响应Js的“Delete”ajax请求,执行删除用户操作
066    ///
067    public ContentResult Delete(string UserId)
068    {
069      try
070      {
071            userModel.Delete(UserId);
072            return Content("删除成功");
073      }
074      catch
075      {
076            return Content("删除失败");
077      }
078    }
079
080    ///
081    /// 响应Js的“Update”ajax请求,执行更新用户操作
082    ///
083    public ContentResult Update(string UserId, string UserName, int Age, string Tel, string Email)
084    {
085      Document doc = new Document();
086      doc["UserId"] = UserId;
087      doc["UserName"] = UserName;
088      doc["Age"] = Age;
089      doc["Tel"] = Tel;
090      doc["Email"] = Email;
091      try
092      {
093            userModel.Update(doc);
094            return Content("修改成功");
095      }
096      catch
097      {
098            return Content("修改失败");
099      }
100    }
101}三、实现模型层数据访问
  最后,我们在Models新建一个Home文件夹,添加模型“UserModel.cs”,实现MongoDB数据库访问代码如下:




01public class UserModel
02{
03    //链接字符串(此处三个字段值根据需要可为读配置文件)
04    public string connectionString = "mongodb://localhost";
05    //数据库名
06    public string databaseName = "myDatabase";
07    //集合名
08    public string collectionName = "userCollection";
09
10    private Mongo mongo;
11    private MongoDatabase mongoDatabase;
12    private MongoCollection mongoCollection;
13
14    public UserModel()
15    {
16      mongo = new Mongo(connectionString);
17      mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
18      mongoCollection = mongoDatabase.GetCollection(collectionName) as MongoCollection;
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 FindAll()
57    {
58      return mongoCollection.FindAll().Documents;
59    }
60
61}四、小结
  代码下载:http://files.iyunv.com/lipan/MongoDB_003.rar
  自此为止一个简单MongoDB表格数据操作的功能就实现完毕了,相信读者在看完这篇文章后,差不多都可以轻松实现MongoDB项目的开发应用了。聪明的你一定会比本文做的功能更完善,更好。下篇计划讲解linq的方式访问数据集合。
页: [1]
查看完整版本: MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据