In my previous MongoDB study note, I led us to learn how to use the samus driver to perform basic data operations. In this article, I learned how to use the jqgrid table to operate MongoDB data in the MVC mode.
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 simpler than the basic ado.net access-related data source. 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". MongoDB's basic data access is implemented at the model layer. Next we will implement it step by step.
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>
-
- </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 Initialization
-
- 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: '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 ("select a line! ");
-
- 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-del ",
-
- Onclickbutton: function (){
-
- VaR id = $ ("# Table1"). getgridparam ("selrow ");
-
- If (ID = NULL ){
-
- Alert ("select a line! ");
- 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 editing status
-
- Function cancel (ID ){
-
- If (ID = "newid") $ ("# Table1"). delrowdata ("newid ");
- Else $ ("# Table1"). restorerow (ID );
-
- }
-
- // Request new data from the 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 ("add data:" + MSG );
-
- $ ("# Table1"). Trigger ("reloadgrid ");
-
- }
-
- });
-
- }
-
- // Send 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 ");
-
- }
-
- });
-
- }
-
- // Request to delete data from the background Ajax
- 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 and provide the data to jqgrid through JSON
-
- /// </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>
-
- /// Respond to the JS "add" ajax request and perform 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>
-
- /// Respond to the JS "delete" ajax request and perform the delete user operation
-
- /// </Summary>
-
- Public contentresult Delete (string userid)
- {
-
- Try
-
- {
-
- Usermodel. Delete (userid );
-
- Return content ("deleted successfully ");
-
- }
-
- Catch
-
- {
-
- Return content ("deletion failed ");
- }
-
- }
-
-
- /// <Summary>
-
- /// Respond to JS's "Update" ajax request and perform 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 collections <document> collections collection;
-
- Public usermodel ()
-
- {
-
- Mongo = new Mongo (connectionstring );
-
- Relational Database = Mongo. getdatabase (databasename) as relational database;
-
- Collect collection = collect database. getcollection <document> (collectionname) As collect 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)
-
- {
-
- Collections 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.
Source: http://www.cnblogs.com/lipan/archive/2011/03/11/1980227.html