See the figure below, which is to realize the basic addition, deletion, query and modification of table data through Jqgrid. Table data addition, deletion, and modification are common functions in the development of general enterprise application systems, but the difference is that the source of this table data is the non-relational database MongoDB. Although the concept of nosql is novel, it is relatively easy to implement the basic application of MongoDB, and even the code is more concise than the basic ADO.net access relational data source. Due to its own “non-relational” data storage method, the link of object-relational mapping is meaningless for MongoDB, so we will not introduce the so-called “ORM” framework to MongoDB.
Next, we will explain step by step how to read MongoDB data in MVC mode and display it on the Jqgrid table in the foreground. The basic design idea of this “simple system” is as follows: we display tables in the view layer, Jqgrid-related Js logic is all placed in a Js file, the control layer implements the four services of “addition, deletion, check and modification”, and the basic data access of MongoDB Implemented on the model layer. Let’s implement it step by step.
the
1. Realize the view layer Jqgrid table logic
First, we create a blank MVC project and add the front-end framework codes of jQuery, jQueryUI, and Jqgrid:
Then create a new view “Index.aspx” under the Home folder of Views, and add the following HTML code to the body tag of the view:
Then create a new Scripts\Home folder, create a new “Index.js” file in this directory, and reference it in the view, the code is as follows:
jQuery(document).ready(function () { //jqGrid initialization jQuery("#table1").jqGrid({ url: '/Home/UserList', datatype: 'json', mtype: 'POST', colNames: ['login name', 'name', 'age', 'mobile number', 'email address', 'operation'], 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: 'User Information Management', hidegrid: false, rownumbers: true, viewrecords: true }).navGrid('#div1', { edit: false, add: false, del: false }) .navButtonAdd('#div1', { caption: "Edit", buttonicon: "ui-icon-add", onClickButton: function () { var id = $("#table1").getGridParam("selrow"); if (id == null) { alert("Please select a row!"); return; } if (id == "newId") return; $("#table1").editRow(id); $("#table1").find("#" + id + "_UserId").attr("readonly","readOnly"); $("#table1").setCell(id, "Edit", ""); } }).navButtonAdd('#div1', { caption: "Delete", buttonicon: "ui-icon-del", onClickButton: function () { var id = $("#table1").getGridParam("selrow"); if (id == null) { alert("Please select a row!"); return; } Delete(id); } }).navButtonAdd('#div1', { caption: "New", buttonicon: "ui-icon-add", onClickButton: function () { $("#table1").addRowData("newId", -1); $("#table1").editRow("newId"); $("#table1").setCell("newId", "Edit", "");} }); }); // cancel editing status function Cancel(id) { if (id == "newId") $("#table1").delRowData("newId"); else $("#table1").restoreRow(id); } //Request new data from background 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(); 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("New data: " + msg); $("#table1").trigger("reloadGrid"); } }); } //Ajax request to the background to update data 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("Modify data: " + msg); $("#table1").trigger("reloadGrid"); } }); } / / Request to the background ajax to delete data function Delete(id) { var UserId = $("#table1").getCell(id, "UserId"); $.ajax({ type: "POST", url: "/Home/Delete", data: "UserId=" + UserId, success: function (msg) { alert("Delete data: " + msg); $("#table1").trigger("reloadGrid"); } }); }
2. Realize the control layer business
Create a new controller “HomeController.cs” under the Controllers directory, four ajax requests are generated in Index.js, and there are four business methods corresponding to the control layer. The HomeController code is as follows:
public class HomeController : Controller { UserModel userModel = new UserModel(); public ActionResult Index() { return View(); } ////// Get a list of all users, and provide data to jqGrid through json /// 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); } ////// Respond to the "Add" ajax request of Js, and perform the add user operation /// 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("Added successfully"); } catch { return Content("Failed to add"); } } ////// Respond to the "Delete" ajax request of Js, and perform the delete user operation /// public ContentResult Delete(string UserId) { try { userModel. Delete(UserId); return Content("Deleted successfully"); } catch { return Content("Delete failed"); } } ////// Respond to the "Update" ajax request of Js, and perform the update user operation /// 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("modified successfully"); } catch { return Content("Modification failed"); } } }
3. Implement model layer data access
Finally, we create a new Home folder in Models, add the model “UserModel.cs”, and implement the MongoDB database access code as follows:
public class UserModel { //Link string (the values of the three fields here can be read configuration files as needed) public string cOnnectionString = "mongodb://localhost"; //Database name public string databaseName = "myDatabase"; //collection name public string collectiOnName = "userCollection"; private Mongo mongo; private MongoDatabase mongoDatabase; private MongoCollection mongoCollection; public UserModel() { mOngo = new Mongo(connectionString); mOngoDatabase = mongo. GetDatabase(databaseName) as MongoDatabase; mOngoCollection= mongoDatabase. GetCollection(collectionName) as MongoCollection; mongo. Connect(); } ~UserModel() { mongo. Disconnect(); } ////// Add a user record /// /// public void Add(Document doc) { mongoCollection. Insert(doc); } ////// Delete a user record /// public void Delete(string UserId) { mongoCollection. Remove(new Document { { "UserId", UserId } }); } ////// Update a user record /// /// public void Update(Document doc) { mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } }); } ////// Find all user records /// /// public IEnumerable FindAll() { return mongoCollection.FindAll().Documents; } }
Four. Summary
Code download: http://files.cnblogs.com/lipan/MongoDB_003.rar
Since then, a simple MongoDB table data operation function has been implemented. I believe that after reading this article, readers can almost easily realize the development and application of MongoDB projects. If you are smart, you will definitely have more complete and better functions than the ones in this article. The next article plans to explain how linq accesses data collections.
the
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(“modified successfully”);
}
catch
{
return Content(“Modification failed”);
}
}
}
3. Implement model layer data access
Finally, we create a new Home folder in Models, add the model “UserModel.cs”, and implement the MongoDB database access code as follows:
public class UserModel { //Link string (the values of the three fields here can be read configuration files as needed) public string cOnnectionString = "mongodb://localhost"; //Database name public string databaseName = "myDatabase"; //collection name public string collectiOnName = "userCollection"; private Mongo mongo; private MongoDatabase mongoDatabase; private MongoCollection mongoCollection; public UserModel() { mOngo = new Mongo(connectionString); mOngoDatabase = mongo. GetDatabase(databaseName) as MongoDatabase; mOngoCollection= mongoDatabase. GetCollection(collectionName) as MongoCollection; mongo. Connect(); } ~UserModel() { mongo. Disconnect(); } ////// Add a user record /// /// public void Add(Document doc) { mongoCollection. Insert(doc); } ////// Delete a user record /// public void Delete(string UserId) { mongoCollection. Remove(new Document { { "UserId", UserId } }); } ////// Update a user record /// /// public void Update(Document doc) { mongoCollection.FindAndModify(doc, new Document { { "UserId", doc["UserId"].ToString() } }); } ////// Find all user records /// /// public IEnumerable FindAll() { return mongoCollection.FindAll().Documents; } }
Four. Summary
Code download: http://files.cnblogs.com/lipan/MongoDB_003.rar
Since then, a simple MongoDB table data operation function has been implemented. I believe that after reading this article, readers can almost easily realize the development and application of MongoDB projects. If you are smart, you will definitely have more complete and better functions than the ones in this article. The next article plans to explain how linq accesses data collections.
the