您的位置:首页 > 数据库 > Mongodb

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

2011-11-24 14:49 746 查看
转载自:http://www.cnblogs.com/lipan/archive/2011/03/11/1980227.html

 

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

view sourceprint?

<
div
>
    
<
table

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

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

show sourceview
sourceprint?

001
jQuery(document).ready(
function

() {
002
 
 
003
    
//jqGrid初始化
004
    
jQuery(
"#table1"
).jqGrid({
005
        
url:
'/Home/UserList'
,
006
        
datatype:
'json'
,

007
        
mtype:
'POST'
,

008
        
colNames: [
'登录名'
,
'姓名'
,

'年龄'
,
'手机号'
,
'邮箱地址'
,

'操作'
],
009
        
colModel: [
010
             
{name:
'UserId'
,index:
'UserId'
,width: 180,editable:
true
},

011
             
{name:
'UserName'
,index:
'UserName'
,width: 200,editable:
true
},

012
             
{name:
'Age'
,index:
'Age'
,width: 150,editable:
true
},

013
             
{name:
'Tel'
,index:
'Tel'
,width: 150,editable:
true
},


014
             
{name:
'Email'
,index:
'Email'
,width: 150,editable:
true
},

015
             
{name:
'Edit'
,index:
'Edit'
,width: 150,editable:
false
,align:
'center'
}
016
             
],
017
        
pager:
'#div1'
,

018
        
postData: {},
019
        
rowNum: 5,
020
        
rowList: [5,10,20],
021
        
sortable:
true
,

022
        
caption:
'用户信息管理'
,

023
        
hidegrid:
false
,

024
        
rownumbers:
true
,

025
        
viewrecords:
true
026
    
}).navGrid(
'#div1'
,{edit:
false
,add:
false
,del:
false
})

027
            
.navButtonAdd(
'#div1'
,{
028
                
caption:
"编辑"
,

029
                
buttonicon:
"ui-icon-add"
,
030
                
onClickButton:
function

() {
031
                    
var

id = $(
"#table1"
).getGridParam(
"selrow"
);
032
                    
if

(id ==
null
) {
033
                        
alert(
"请选择行!"
);
034
                        
return
;
035
                    
}
036
                    
if

(id ==
"newId"
)
return
;

037
                    
$(
"#table1"
).editRow(id);
038
                    
$(
"#table1"
).find(
"#"

+id +
"_UserId"
).attr(
"readonly"
,
"readOnly"
);
039
                    
$(
"#table1"
).setCell(id,
"Edit"
,

"<input id='Button1' type='button' value='提交' onclick='Update(\""

+id +
"\")' /><input id='Button2' type='button' value='取消' onclick='Cancel(\""

+id +
"\")' />"
);
040
                
}
041
            
}).navButtonAdd(
'#div1'
,{
042
                
caption:
"删除"
,

043
                
buttonicon:
"ui-icon-del"
,
044
                
onClickButton:
function

() {
045
                    
var

id = $(
"#table1"
).getGridParam(
"selrow"
);
046
                    
if

(id ==
null
) {
047
                        
alert(
"请选择行!"
);
048
                        
return
;
049
                    
}
050
                    
Delete(id);
051
                
}
052
            
}).navButtonAdd(
'#div1'
,{
053
                
caption:
"新增"
,

054
                
buttonicon:
"ui-icon-add"
,
055
                
onClickButton:
function

() {
056
                    
$(
"#table1"
).addRowData(
"newId"
,-1);
057
                    
$(
"#table1"
).editRow(
"newId"
);
058
                    
$(
"#table1"
).setCell(
"newId"
,
"Edit"
,

"<input id='Button1' type='button' value='提交' onclick='Add()' /><input id='Button2' type='button' value='取消' onclick='Cancel(\"newId\")' />"
);
059
                
}
060
            
});
061
});
062
 
 
063
//取消编辑状态
064
function
Cancel(id) {
065
    
if

(id ==
"newId"
) $(
"#table1"
).delRowData(
"newId"
);
066
    
else

$(
"#table1"
).restoreRow(id);
067
}
068
 
 
069
//向后台ajax请求新增数据
070
function

Add() {
071
    
var

UserId = $(
"#table1"
).find(
"#newId"

+
"_UserId"
).val();
072
    
var

UserName = $(
"#table1"
).find(
"#newId"

+
"_UserName"
).val();
073
    
var

Age = $(
"#table1"
).find(
"#newId"

+
"_Age"
).val();
074
    
var

Tel = $(
"#table1"
).find(
"#newId"

+
"_Tel"
).val();
075
    
var

Email = $(
"#table1"
).find(
"#newId"

+
"_Email"
).val();
076
 
 
077
    
$.ajax({
078
        
type:
"POST"
,

079
        
url:
"/Home/Add"
,
080
        
data:
"UserId="

+UserId +
"&UserName="

+UserName +
"&Age="

+Age +
"&Tel="

+Tel +
"&Email="

+Email,
081
        
success:
function
(msg) {
082
            
alert(
"新增数据: "

+msg);
083
            
$(
"#table1"
).trigger(
"reloadGrid"
);
084
        
}
085
    
});
086
}
087
 
 
088
//向后台ajax请求更新数据
089
function
Update(id) {
090
    
var

UserId = $(
"#table1"
).find(
"#"

+id +
"_UserId"
).val();
091
    
var

UserName = $(
"#table1"
).find(
"#"

+id +
"_UserName"
).val();
092
    
var

Age = $(
"#table1"
).find(
"#"

+id +
"_Age"
).val();
093
    
var

Tel = $(
"#table1"
).find(
"#"

+id +
"_Tel"
).val();
094
    
var

Email = $(
"#table1"
).find(
"#"

+id +
"_Email"
).val();
095
 
 
096
    
$.ajax({
097
        
type:
"POST"
,

098
        
url:
"/Home/Update"
,
099
        
data:
"UserId="

+UserId +
"&UserName="

+UserName +
"&Age="

+Age +
"&Tel="

+Tel +
"&Email="

+Email,
100
        
success:
function
(msg) {
101
            
alert(
"修改数据: "

+msg);
102
            
$(
"#table1"
).trigger(
"reloadGrid"
);
103
        
}
104
    
});
105
}
106
 
 
107
//向后台ajax请求删除数据
108
function
Delete(id) {
109
    
var

UserId = $(
"#table1"
).getCell(id,
"UserId"
);
110
    
$.ajax({
111
        
type:
"POST"
,

112
        
url:
"/Home/Delete"
,
113
        
data:
"UserId="

+UserId,
114
        
success:
function
(msg) {
115
            
alert(
"删除数据: "

+msg);
116
            
$(
"#table1"
).trigger(
"reloadGrid"
);
117
        
}
118
    
});
119
}

二、实现控制层业务

  在Controllers目录下新建控制器“HomeController.cs”,Index.js中产生了四个ajax请求,对应控制层也有四个业务方法。HomeController代码如下:

view sourceprint?

001
public
class
HomeController : Controller
002
{
003
    
UserModeluserModel =
new
UserModel();
004
    
public

ActionResult Index()
005
    
{

006
        
return

View();
007
    
}

008
 
009
    
/// <summary>
010
    
/// 获取全部用户列表,通过json将数据提供给jqGrid
011
    
/// </summary>
012
    
public

JsonResult UserList(
string

sord,
string

sidx,
string

rows,
string

page)
013
    
{

014
        
var list= userModel.FindAll();
015
        
int

i = 0;
016
        
var query = from u
in
list

017
                    
select
new
018
                    
{
019
                        
id = i++,
020
                        
cell =
new
string
[]{
021
                            
u[
"UserId"
].ToString(),
022
                            
u[
"UserName"
].ToString(),
023
                            
u[
"Age"
].ToString(),
024
                            
u[
"Tel"
].ToString(),
025
                            
u[
"Email"
].ToString(),
026
                            
"-"
027
                        
}
028
                    
};
029
 
030
        
var data =
new
031
        
{
032
            
total = query.Count() / Convert.ToInt32(rows) +1,
033
            
page = Convert.ToInt32(page),
034
            
records = query.Count(),
035
            
rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page)- 1)).Take(Convert.ToInt32(rows))
036
        
};
037
 
038
        
return

Json(data,JsonRequestBehavior.AllowGet);
039
    
}

040
 
041
    
/// <summary>
042
    
/// 响应Js的“Add”ajax请求,执行添加用户操作
043
    
/// </summary>
044
    
public

ContentResult Add(
string

UserId,
string

UserName,
int

Age,
string

Tel,
string

Email)
045
    
{

046
        
Document doc =
new
Document();
047
        
doc[
"UserId"
] = UserId;
048
        
doc[
"UserName"
] = UserName;
049
        
doc[
"Age"
] = Age;
050
        
doc[
"Tel"
] = Tel;
051
        
doc[
"Email"
] = Email;
052
 
053
        
try
054
        
{
055
            
userModel.Add(doc);
056
            
return

Content(
"添加成功"
);
057
        
}
058
        
catch
059
        
{
060
            
return

Content(
"添加失败"
);
061
        
}
062
    
}

063
 
064
    
/// <summary>
065
    
/// 响应Js的“Delete”ajax请求,执行删除用户操作
066
    
/// </summary>
067
    
public

ContentResult Delete(
string

UserId)
068
    
{

069
        
try
070
        
{
071
            
userModel.Delete(UserId);
072
            
return

Content(
"删除成功"
);
073
        
}
074
        
catch
075
        
{
076
            
return

Content(
"删除失败"
);
077
        
}
078
    
}

079
 
080
    
/// <summary>
081
    
/// 响应Js的“Update”ajax请求,执行更新用户操作
082
    
/// </summary>
083
    
public

ContentResult Update(
string

UserId,
string

UserName,
int

Age,
string

Tel,
string

Email)
084
    
{

085
        
Document doc =
new
Document();
086
        
doc[
"UserId"
] = UserId;
087
        
doc[
"UserName"
] = UserName;
088
        
doc[
"Age"
] = Age;
089
        
doc[
"Tel"
] = Tel;
090
        
doc[
"Email"
] = Email;
091
        
try
092
        
{
093
            
userModel.Update(doc);
094
            
return

Content(
"修改成功"
);
095
        
}
096
        
catch
097
        
{
098
            
return

Content(
"修改失败"
);
099
        
}
100
    
}

101
}

三、实现模型层数据访问

  最后,我们在Models新建一个Home文件夹,添加模型“UserModel.cs”,实现MongoDB数据库访问代码如下:

view sourceprint?

01
public
class
UserModel
02
{
03
    
//链接字符串(此处三个字段值根据需要可为读配置文件)
04
    
public

string
connectionString =
"mongodb://localhost"
;
05
    
//数据库名
06
    
public

string
databaseName =
"myDatabase"
;
07
    
//集合名 
08
    
public

string
collectionName =
"userCollection"
;
09
 
10
    
private

Mongo mongo;
11
    
private

MongoDatabase mongoDatabase;
12
    
private

MongoCollection<Document>mongoCollection;
13
 
14
    
public

UserModel()
15
    
{

16
        
mongo =
new
Mongo(connectionString);
17
        
mongoDatabase = mongo.GetDatabase(databaseName)
as
MongoDatabase;
18
        
mongoCollection = mongoDatabase.GetCollection<Document>(collectionName)
as
MongoCollection<Document>;
19
        
mongo.Connect();
20
    
}

21
    
~UserModel()
22
    
{

23
        
mongo.Disconnect();
24
    
}

25
 
26
    
/// <summary>
27
    
/// 增加一条用户记录
28
    
/// </summary>
29
    
/// <param name="doc"></param>
30
    
public

void
Add(Document doc)
31
    
{

32
        
mongoCollection.Insert(doc);
33
    
}

34
 
35
    
/// <summary>
36
    
/// 删除一条用户记录
37
    
/// </summary>
38
    
public

void
Delete(
string

UserId)
39
    
{

40
        
mongoCollection.Remove(
new

Document {{
"UserId"
,UserId }});
41
    
}

42
 
43
    
/// <summary>
44
    
/// 更新一条用户记录
45
    
/// </summary>
46
    
/// <param name="doc"></param>
47
    
public

void
Update(Document doc)
48
    
{

49
        
mongoCollection.FindAndModify(doc,
new
Document {{
"UserId"
,doc[
"UserId"
].ToString() }});
50
    
}

51
 
52
    
/// <summary>
53
    
/// 查找所有用户记录
54
    
/// </summary>
55
    
/// <returns></returns>
56
    
public

IEnumerable<Document>FindAll() 
57
    
{

58
        
return

mongoCollection.FindAll().Documents;
59
    
}

60
 
61
}

四、小结

  代码下载:http://files.cnblogs.com/lipan/MongoDB_003.rar

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

作者:李盼(Lipan)

出处:[Lipan]http://www.cnblogs.com/lipan/

版权声明:本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐