侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB数据

数据库  /  管理员 发布于 5年前   283

看到下图,是通过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代码:

复制代码 代码如下:
<div>
    <table id="table1">
    </table>
    <div id="div1">
    </div>
</div>

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

复制代码 代码如下:
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代码如下:

复制代码 代码如下:
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数据库访问代码如下:

复制代码 代码如下:
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;
    } 
}

四、小结

  代码下载:MongoDB_003.rar

  自此为止一个简单MongoDB表格数据操作的功能就实现完毕了,相信读者在看完这篇文章后,差不多都可以轻松实现MongoDB项目的开发应用了。聪明的你一定会比本文做的功能更完善,更好。下篇计划讲解linq的方式访问数据集合。

作者:李盼(Lipan)
出处:[Lipan] (http://www.cnblogs.com/lipan/)


  • 上一条:
    MongoDB学习笔记(四) 用MongoDB的文档结构描述数据关系
    下一条:
    MongoDB学习笔记(二) 通过samus驱动实现基本数据操作
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客