白云岛资源网 Design By www.pvray.com
看到下图,是通过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/)

白云岛资源网 Design By www.pvray.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
白云岛资源网 Design By www.pvray.com