萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

MongoDB 學習筆記(三):MVC 架構下整合 JqGrid 實現 MongoDB 資料增刪改查

專案架構概覽

採用 MVC 模式:視圖層呈現 JqGrid 表格,JS 邏輯集中於單一檔案;控制器層實作增刪查改業務;模型層封裝 MongoDB 基礎資料存取。NoSQL 特性使 ORM 框架變得多餘,程式碼比傳統 ADO.NET 更簡潔。

一、視圖層:JqGrid 表格與互動邏輯

1. Index.aspx 基礎結構

<div>
    <table id="table1"></table>
    <div id="div1"></div>
</div>

2. Index.js:JqGrid 初始化與工具列按鈕

jQuery(document).ready(function () {
    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) { 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) { alert("請選擇行!"); return; }
            Delete(id);
        }
    }).navButtonAdd('#div1', {
        caption: "新增",
        buttonicon: "ui-icon-plus",
        onClickButton: function () {
            $("#table1").addRow("newId", {}, "first");
            $("#table1").editRow("newId");
            $("#table1").setCell("newId", "Edit", "<input id='Button1' type='button' value='提交' onclick='Create()' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"newId\")' />");
        }
    });
});

二、控制器層:HomeController.cs

public class HomeController : Controller
{
    UserBLL userBll = new UserBLL();

    public ActionResult Index() { return View(); }

    public JsonResult UserList(string sidx, string sord, int page, int rows)
    {
        int totalRecords = userBll.GetCount();
        var users = userBll.GetPagedList(page, rows, sidx, sord);
        var jsonData = new
        {
            total = (totalRecords + rows - 1) / rows,
            page = page,
            records = totalRecords,
            rows = users
        };
        return Json(jsonData);
    }

    [HttpPost]
    public string Create(UserInfo user) { userBll.Insert(user); return "success"; }
    [HttpPost]
    public string Update(UserInfo user) { userBll.Update(user); return "success"; }
    [HttpPost]
    public string Delete(string id) { userBll.Delete(id); return "success"; }
}

三、模型層:UserBLL 核心資料存取

public class UserBLL
{
    private MongoCollection<Document> mongoCollection;

    public UserBLL()
    {
        var mongo = new Mongo("mongodb://localhost");
        var db = mongo.GetDatabase("myDatabase") as MongoDatabase;
        mongoCollection = db.GetCollection<Document>("UserInfo") as MongoCollection<Document>;
        mongo.Connect();
    }

    public int GetCount() { return (int)mongoCollection.Count(); }

    public List<Document> GetPagedList(int page, int rows, string sidx, string sord)
    {
        var query = Query.Null;
        var sort = new Document { { sidx, sord == "asc" ? 1 : -1 } };
        return mongoCollection.Find(query)
            .SetSortOrder(sort)
            .SetSkip((page - 1) * rows)
            .SetLimit(rows)
            .Documents.ToList();
    }

    public void Insert(UserInfo user)
    {
        var doc = new Document
        {
            { "UserId", user.UserId },
            { "UserName", user.UserName },
            { "Age", user.Age },
            { "Tel", user.Tel },
            { "Email", user.Email }
        };
        mongoCollection.Insert(doc);
    }

    public void Update(UserInfo user)
    {
        var query = Query.EQ("UserId", user.UserId);
        var update = Update.Set("UserName", user.UserName)
            .Set("Age", user.Age).Set("Tel", user.Tel).Set("Email", user.Email);
        mongoCollection.Update(query, update);
    }

    public void Delete(string id)
    {
        mongoCollection.Remove(Query.EQ("UserId", id));
    }
}

總結

MVC + JqGrid + MongoDB 的組合讓企業級應用的表格操作開發極為輕量,充分發揮文件資料庫 Schema-free 的靈活優勢。

copyright © 萬盛學電腦網 all rights reserved