下面我们将逐步讲解怎么在MVC模式下将MongoDB数据读取,并展示在前台Jqgrid表格上。这个“简易系统”的基本设计思想是这样的:我们在视图层展示表格,Jqgrid相关Js逻辑全部放在一个Js文件中,控制层实现了“增删查改”四个业务,MongoDB的基本数据访问放在了模型层实现。下面我们一步步实现。 www.2cto.com
接着新建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", "");
}
}).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", "");
}
});
});
//取消编辑状态
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