We can see that jqgrid is used to add, query, modify, and delete table data. Table Data addition, deletion, and modification are common functions developed by enterprise application systems. However, the difference is that the table data source is non-relational database MongoDB. Although nosql is a new concept, it is easy to implement the basic application of MongoDB.CodeIt is more concise than the basic link data source for access to ado.net. Because of its "non-relational" data storage method, object link ing is meaningless for MongoDB. Therefore, we will not introduce the so-called "ORM" framework to MongoDB.
Next we will gradually explain how to read MongoDB data in MVC mode and display it on the jqgrid table at the front end. The basic design concept of this "Simple System" is as follows: we display tables on the view layer, and all jqgrid-related JS logic is placed in a JS file, the control layer implements four services: add, delete, query, and modify. The basic data access of MongoDB is implemented at the model layer. Next we will implement it step by step.
Series directory
MongoDB Study Notes (1) Introduction and installation of MongoDB
MongoDB Study Notes (2) use the samus driver to perform basic data operations
MongoDB learning notes (3) using jqgrid tables to operate MongoDB data in MVC Mode
MongoDB learning notes (4) describe the data relationship using the document structure of MongoDB
MongoDB Study Notes (5) MongoDB File Access Operations
MongoDB Study Notes (6) MongoDB index usage and Efficiency Analysis
I. Implement jqgrid table logic at the view layer
First, create a blank MVC project and add the front-end framework code of jquery, jqueryui, and jqgrid:
Create the view "index. aspx" in the home folder of views and add the following HTML code to the view Body Tag:
<Div> <Table id = "Table1"> </table> <Div id = "div1"> </div>
Create the scripts \ home folder, create the "index. js" file in the directory, and reference it as shown in the figure. The Code is as follows:
Jquery (document ). ready (function () {// jqgrid initializes jquery ("# Table1 "). jqgrid ({URL: '/home/userlist', datatype: 'json', mtype: 'post', colnames: ['login name', 'name', 'age ', 'mobile phone 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: 'e-mail', 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 informationmanagement', 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 ("select a row! "); 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 = 'Submit' onclick = 'Update (\" "+ ID + "\") '/> <input id = 'button2' type = 'button' value = 'cancel 'onclick = 'cancel (\ "" + ID + "\") '/> ");}}). navbuttonadd ('# div1', {caption: "delete", buttonicon: "UI-icon-de L ", onclickbutton: function () {var id = $ (" # Table1 "). getgridparam ("selrow"); If (ID = NULL) {alert ("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", "<input id = 'button1' type = 'button 'value = 'submit 'onclick = 'add () '/> <input id = 'button2' type = 'button' value = 'cancel 'onclick = 'cancel (\ "newid \") '/> ") ;}}) ;}; // cancel the function cancel (ID) {If (ID =" newid ") $ ("# Table1 "). delrowdata ("newid"); else $ ("# Table1 "). restorerow (ID);} // Add data function add () {var userid = $ ("# Table1") to the background Ajax request "). 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") ;}}) ;}// sends an Ajax request to the background to update the 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") ;}}) ;}// call the background Ajax request to delete the 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. Implement control layer services
Create the controller "homecontroller. cs" in the controllers directory. Index. js generates four Ajax requests, and the corresponding control layer also has four business methods. The homecontroller code is as follows:
Public class homecontroller: controller {usermodel = new usermodel (); Public actionresult index () {return view () ;}/// <summary> /// obtain the list of all users, provide data to 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> // responds to the JS "add" ajax request and executes the add user operation. /// </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 ("added successfully") ;}catch {return content ("failed to add ");}} /// <summary> /// responds to the JS "delete" ajax request and executes the delete user operation. /// </Summary> Public contentresult Delete (string userid) {try {usermodel. delete (userid); Return content ("deleted successfully") ;}catch {return content ("failed to delete ");}} /// <summary> /// respond to the JS "Update" ajax request and execute the update user operation // </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 ("modified successfully") ;}catch {return content ("failed to modify ");}}}
3. Data access at the model layer
Finally, create a home folder in models and add the model "usermodel. cs". The MongoDB database access code is as follows:
Public class usermodel {// link string (the three field values can be used as needed to read the configuration file) Public String connectionstring = "MongoDB: // localhost "; // database name Public String databasename = "mydatabase"; // Set Name Public String collectionname = "usercollection"; private Mongo; private relational database; private relational collection <document> relational collection; public usermodel () {Mongo = new Mongo (connectionstring); Relational Database = Mong O. getdatabase (databasename) as your database; collections collection = your database. getcollection <document> (collectionname) as your collection <document>; Mongo. Connect ();}~ Usermodel () {Mongo. disconnect ();} /// <summary> /// Add a user record /// </Summary> /// <Param name = "Doc"> </param> Public void add (document DOC) {collections collection. insert (DOC) ;}//< summary> /// delete a user record /// </Summary> Public void Delete (string userid) {empty collection. remove (new document {"userid", userid }});} /// <summary> /// update a user record /// </Summary> /// <Param name = "Doc"> </param> Public void Update (document DOC) {collections collection. findandmodify (Doc, new document {"userid", Doc ["userid"]. tostring ()}});} /// <summary> /// query all user records /// </Summary> /// <returns> </returns> Public ienumerable <document> findall () {return response collection. findall (). documents ;}}
Iv. Summary
Code download: http://files.cnblogs.com/lipan/MongoDB_003.rar
Since then, a simple MongoDB table data operation function has been completed.ArticleLater, you can easily implement the development and application of the MongoDB project. If you are smart, you will certainly be better and better than the functions provided in this Article. In the next article, we will explain how to access the data set by using LINQ.
By Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan)
Copyright: The copyright of this article is shared by the author and the blog. The detailed link of this article must be noted during reprinting; otherwise, the author will be held legally liable.