MongoDB學(xué)習(xí)筆記(三) 在MVC模式下通過Jqgrid表格操作MongoDB數(shù)據(jù)
下面我們將逐步講解怎么在MVC模式下將MongoDB數(shù)據(jù)讀取,并展示在前臺(tái)Jqgrid表格上。這個(gè)“簡易系統(tǒng)”的基本設(shè)計(jì)思想是這樣的:我們在視圖層展示表格,Jqgrid相關(guān)Js邏輯全部放在一個(gè)Js文件中,控制層實(shí)現(xiàn)了“增刪查改”四個(gè)業(yè)務(wù),MongoDB的基本數(shù)據(jù)訪問放在了模型層實(shí)現(xiàn)。下面我們一步步實(shí)現(xiàn)。
一、實(shí)現(xiàn)視圖層Jqgrid表格邏輯
首先,我們新建一個(gè)MVC空白項(xiàng)目,添加好jQuery、jQueryUI、Jqgrid的前端框架代碼:
然后在Views的Home文件夾下新建視圖“Index.aspx”,在視圖的body標(biāo)簽中添加如下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: ['登錄名', '姓名', '年齡', '手機(jī)號', '郵箱地址', '操作'],
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\")' />");
}
});
});
//取消編輯狀態(tài)
function Cancel(id) {
if (id == "newId") $("#table1").delRowData("newId");
else $("#table1").restoreRow(id);
}
//向后臺(tái)ajax請求新增數(shù)據(jù)
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("新增數(shù)據(jù): " + msg);
$("#table1").trigger("reloadGrid");
}
});
}
//向后臺(tái)ajax請求更新數(shù)據(jù)
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("修改數(shù)據(jù): " + msg);
$("#table1").trigger("reloadGrid");
}
});
}
//向后臺(tái)ajax請求刪除數(shù)據(jù)
function Delete(id) {
var UserId = $("#table1").getCell(id, "UserId");
$.ajax({
type: "POST",
url: "/Home/Delete",
data: "UserId=" + UserId,
success: function (msg) {
alert("刪除數(shù)據(jù): " + msg);
$("#table1").trigger("reloadGrid");
}
});
}
二、實(shí)現(xiàn)控制層業(yè)務(wù)
在Controllers目錄下新建控制器“HomeController.cs”,Index.js中產(chǎn)生了四個(gè)ajax請求,對應(yīng)控制層也有四個(gè)業(yè)務(wù)方法。HomeController代碼如下:
public class HomeController : Controller
{
UserModel userModel = new UserModel();
public ActionResult Index()
{
return View();
}
/// <summary>
/// 獲取全部用戶列表,通過json將數(shù)據(jù)提供給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>
/// 響應(yīng)Js的“Add”ajax請求,執(zhí)行添加用戶操作
/// </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>
/// 響應(yīng)Js的“Delete”ajax請求,執(zhí)行刪除用戶操作
/// </summary>
public ContentResult Delete(string UserId)
{
try
{
userModel.Delete(UserId);
return Content("刪除成功");
}
catch
{
return Content("刪除失敗");
}
}
/// <summary>
/// 響應(yīng)Js的“Update”ajax請求,執(zhí)行更新用戶操作
/// </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("修改失敗");
}
}
}
三、實(shí)現(xiàn)模型層數(shù)據(jù)訪問
最后,我們在Models新建一個(gè)Home文件夾,添加模型“UserModel.cs”,實(shí)現(xiàn)MongoDB數(shù)據(jù)庫訪問代碼如下:
public class UserModel
{
//鏈接字符串(此處三個(gè)字段值根據(jù)需要可為讀配置文件)
public string connectionString = "mongodb://localhost";
//數(shù)據(jù)庫名
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;
}
}
四、小結(jié)
代碼下載:MongoDB_003.rar
自此為止一個(gè)簡單MongoDB表格數(shù)據(jù)操作的功能就實(shí)現(xiàn)完畢了,相信讀者在看完這篇文章后,差不多都可以輕松實(shí)現(xiàn)MongoDB項(xiàng)目的開發(fā)應(yīng)用了。聰明的你一定會(huì)比本文做的功能更完善,更好。下篇計(jì)劃講解linq的方式訪問數(shù)據(jù)集合。
作者:李盼(Lipan)
出處:[Lipan] (http://www.cnblogs.com/lipan/)
相關(guān)文章
集群運(yùn)維自動(dòng)化工具ansible之使用playbook安裝zabbix客戶端
Zabbix客戶端的安裝配置:Zabbix是一個(gè)基于WEB界面的提供分布式系統(tǒng)監(jiān)視以及網(wǎng)絡(luò)監(jiān)視功能的企業(yè)級的開源解決方案。zabbix能監(jiān)視各種網(wǎng)絡(luò)參數(shù),保證服務(wù)器系統(tǒng)的安全運(yùn)營;本文講述的是使用playbook安裝zabbix客戶端。2014-07-07http狀態(tài)碼匯總及問題經(jīng)驗(yàn)總結(jié)
網(wǎng)站的http狀態(tài)對于網(wǎng)站維護(hù)人員來說是相當(dāng)重要的,當(dāng)網(wǎng)站出現(xiàn)問題的時(shí)候,我們首先要診斷一下網(wǎng)站的http狀態(tài),從而進(jìn)一步確認(rèn)哪里出現(xiàn)的問題2013-11-11Apache?Hudi基于華米科技應(yīng)用湖倉一體化改造
這篇文章主要介紹了Apache?Hudi基于華米科技應(yīng)用湖倉一體化改造?,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-03-03阿里云k8s服務(wù)springboot項(xiàng)目應(yīng)用升級時(shí)出現(xiàn)502錯(cuò)誤
這篇文章主要介紹了阿里云k8s服務(wù)springboot項(xiàng)目應(yīng)用升級時(shí)出現(xiàn)502錯(cuò)誤,需要的朋友可以參考下2022-04-04XAMPP下使用頂級域名綁定虛擬主機(jī)的配置方法和示例
這篇文章主要介紹了XAMPP下使用頂級域名綁定虛擬主機(jī)的配置方法和示例,XAMPP是Windows下非常好用的一款集成開發(fā)環(huán)境,需要的朋友可以參考下2014-07-07SSH端口轉(zhuǎn)發(fā),本地端口轉(zhuǎn)發(fā),遠(yuǎn)程端口轉(zhuǎn)發(fā),動(dòng)態(tài)端口轉(zhuǎn)發(fā)詳解
本文為大家詳細(xì)介紹了SSH端口轉(zhuǎn)發(fā),本地端口轉(zhuǎn)發(fā),遠(yuǎn)程端口轉(zhuǎn)發(fā),動(dòng)態(tài)端口轉(zhuǎn)發(fā)等相關(guān)知識(shí)2018-10-10用 Win2003 架設(shè)郵件服務(wù)器 圖文詳解
很多企業(yè)局域網(wǎng)內(nèi)都架設(shè)了郵件服務(wù)器,用于進(jìn)行公文發(fā)送和工作交流。但使用專業(yè)的企業(yè)郵件系統(tǒng)軟件需要大量的資金投入,這對于很多企業(yè)來說是無法承受的2012-10-10git修改和刪除功能_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了git修改和刪除功能,需要的朋友可以參考下2017-08-08