MongoDB學(xué)習(xí)筆記(三) 在MVC模式下通過(guò)Jqgrid表格操作MongoDB數(shù)據(jù)
下面我們將逐步講解怎么在MVC模式下將MongoDB數(shù)據(jù)讀取,并展示在前臺(tái)Jqgrid表格上。這個(gè)“簡(jiǎn)易系統(tǒng)”的基本設(shè)計(jì)思想是這樣的:我們?cè)谝晥D層展示表格,Jqgrid相關(guān)Js邏輯全部放在一個(gè)Js文件中,控制層實(shí)現(xiàn)了“增刪查改”四個(gè)業(yè)務(wù),MongoDB的基本數(shù)據(jù)訪問(wèn)放在了模型層實(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ī)號(hào)', '郵箱地址', '操作'],
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("請(qǐng)選擇行!");
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("請(qǐng)選擇行!");
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請(qǐng)求新增數(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請(qǐng)求更新數(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請(qǐng)求刪除數(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請(qǐng)求,對(duì)應(yīng)控制層也有四個(gè)業(yè)務(wù)方法。HomeController代碼如下:
public class HomeController : Controller
{
UserModel userModel = new UserModel();
public ActionResult Index()
{
return View();
}
/// <summary>
/// 獲取全部用戶列表,通過(guò)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請(qǐng)求,執(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請(qǐng)求,執(zhí)行刪除用戶操作
/// </summary>
public ContentResult Delete(string UserId)
{
try
{
userModel.Delete(UserId);
return Content("刪除成功");
}
catch
{
return Content("刪除失敗");
}
}
/// <summary>
/// 響應(yīng)Js的“Update”ajax請(qǐng)求,執(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ù)訪問(wèn)
最后,我們?cè)贛odels新建一個(gè)Home文件夾,添加模型“UserModel.cs”,實(shí)現(xiàn)MongoDB數(shù)據(jù)庫(kù)訪問(wèn)代碼如下:
public class UserModel
{
//鏈接字符串(此處三個(gè)字段值根據(jù)需要可為讀配置文件)
public string connectionString = "mongodb://localhost";
//數(shù)據(jù)庫(kù)名
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è)簡(jiǎn)單MongoDB表格數(shù)據(jù)操作的功能就實(shí)現(xiàn)完畢了,相信讀者在看完這篇文章后,差不多都可以輕松實(shí)現(xiàn)MongoDB項(xiàng)目的開(kāi)發(fā)應(yīng)用了。聰明的你一定會(huì)比本文做的功能更完善,更好。下篇計(jì)劃講解linq的方式訪問(wèn)數(shù)據(jù)集合。
作者:李盼(Lipan)
出處:[Lipan] (http://www.cnblogs.com/lipan/)
相關(guān)文章
win11安裝wsl報(bào)錯(cuò)之無(wú)法解析服務(wù)器的名稱或地址的問(wèn)題及解決方法
項(xiàng)目開(kāi)發(fā)中,需要用到wsl,因此根據(jù)wsl官方(WSL安裝教程)命令?wsl --install 進(jìn)行wsl的安裝,本文主要是記錄自己在安裝wsl中遇到的問(wèn)題"無(wú)法解析服務(wù)器的名稱或地址"的解決辦法,感興趣的朋友一起看看吧2024-04-04
寶塔通過(guò)composer安裝TP依賴的詳細(xì)教程(寶塔服務(wù)器)
這篇文章主要介紹了寶塔通過(guò)composer安裝TP依賴的詳細(xì)教程(寶塔服務(wù)器),本文給大家分享問(wèn)題原因分析及解決方案,需要的朋友可以參考下2023-06-06
memcached常用命令_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了memcached常用命令,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
Dell R730服務(wù)器6i陣列卡Raid5配置方法(熱備)
這篇文章主要介紹了Dell R730服務(wù)器6i陣列卡Raid5配置方法,需要的朋友可以參考下2018-05-05
MongoDB學(xué)習(xí)筆記(二) 通過(guò)samus驅(qū)動(dòng)實(shí)現(xiàn)基本數(shù)據(jù)操作
傳統(tǒng)的關(guān)系數(shù)據(jù)庫(kù)一般由數(shù)據(jù)庫(kù)(database)、表(table)、記錄(record)三個(gè)層次概念組成,MongoDB是由(database)、集合(collection)、文檔對(duì)象(document)三個(gè)層次組成2013-07-07
startssl申請(qǐng)SSL證書(shū) 并且配置 iis 啟用https協(xié)議
這篇文章主要介紹了startssl申請(qǐng)SSL證書(shū) 并且配置 iis 啟用https協(xié)議,需要的朋友可以參考下2017-03-03
服務(wù)器錯(cuò)誤碼500 501 502 503 504 505 詳解
這篇文章主要介紹了服務(wù)器錯(cuò)誤碼500 501 502 503 504 505 詳解,需要的朋友可以參考下2015-07-07

