设为首页 收藏本站
查看: 1123|回复: 0

[经验分享] MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据

[复制链接]
YunVN网友  发表于 2015-7-9 12:00:51 |阅读模式
  看到下图,是通过Jqgrid实现表格数据的基本增删查改的操作。表格数据增删改是一般企业应用系统开发的常见功能,不过不同的是这个表格数据来源 是非关系型的数据库MongoDB。nosql虽然概念新颖,但是MongoDB基本应用实现起来还是比较轻松的,甚至代码比基本的ADO.net访问关 系数据源还要简洁。由于其本身的“非关系”的数据存储方式,使得对象关系映射这个环节对于MongoDB来讲显得毫无意义,因此我们也不会对 MongoDB引入所谓的“ORM”框架。
DSC0000.jpg
  下面我们将逐步讲解怎么在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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84798-1-1.html 上篇帖子: MapReduce with MongoDB and Python 下篇帖子: MongoDB学习笔记~Mongo集群和副本集
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表