MongoDB learning notes (3) using jqgrid tables to operate MongoDB data in MVC Mode

Source: Internet
Author: User
Tags setcell jqgrid

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:

  
  
  1. <Div>
  2.  
  3. <Table id = "Table1">
  4.  
  5. </Table>
  6.  
  7. <Div id = "div1">
  8.  
  9. </Div>
  10.  
  11. </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:

 
 
  1. Jquery (document). Ready (function (){
  2. // Jqgrid Initialization
  3. Jquery ("# Table1"). jqgrid ({
  4. URL: '/home/userlist ',
  5. Datatype: 'json ',
  6. Mtype: 'post ',
  7. Colnames: ['login name', 'name', 'age', 'mobile phone number', 'email address', 'operation'],
  8. Colmodel :[
  9. {Name: 'userid', index: 'userid', width: 180, Editable: true },
  10. {Name: 'username', index: 'username', width: 200, Editable: true },
  11. {Name: 'age', index: 'age', width: 150, Editable: true },
  12. {Name: 'tel', index: 'tel', width: 150, Editable: true },
  13. {Name: 'email ', index: 'email', width: 150, Editable: true },
  14. {Name: 'edit', index: 'edit', width: 150, Editable: false, align: 'center '}
  15. ],
  16. Pager: '# div1 ',
  17. Postdata :{},
  18. Rownum: 5,
  19. Rowlist: [5, 10, 20],
  20. Sortable: True,
  21. Caption: 'user information management ',
  22. Hidegrid: false,
  23. Rownumbers: True,
  24. Viewrecords: True
  25. }). Navgrid ('# div1', {EDIT: false, add: false, del: false })
  26. . Navbuttonadd ('# div1 ',{
  27. Caption: "edit ",
  28. Buttonicon: "UI-icon-Add ",
  29. Onclickbutton: function (){
  30. VaR id = $ ("# Table1"). getgridparam ("selrow ");
  31. If (ID = NULL ){
  32. Alert ("select a line! ");
  33. Return;
  34. }
  35. If (ID = "newid") return;
  36. $ ("# Table1"). editrow (ID );
  37. $ ("# Table1"). Find ("#" + ID + "_ userid"). ATTR ("readonly", "readonly ");
  38. $ ("# Table1 "). setcell (ID, "edit ", "<input id = 'button1' type = 'button 'value = 'Submit' onclick = 'Update (\" "+ ID + "\") '/> <input id = 'button2' type = 'button' value = 'cancel 'onclick = 'cancel (\ "" + ID + "\") '/> ");
  39. }
  40. }). Navbuttonadd ('# div1 ',{
  41. Caption: "delete ",
  42. Buttonicon: "UI-icon-del ",
  43. Onclickbutton: function (){
  44. VaR id = $ ("# Table1"). getgridparam ("selrow ");
  45. If (ID = NULL ){
  46. Alert ("select a line! ");
  47. Return;
  48. }
  49. Delete (ID );
  50. }
  51. }). Navbuttonadd ('# div1 ',{
  52. Caption: "new ",
  53. Buttonicon: "UI-icon-Add ",
  54. Onclickbutton: function (){
  55. $ ("# Table1"). addrowdata ("newid",-1 );
  56. $ ("# Table1"). editrow ("newid ");
  57. $ ("# Table1 "). setcell ("newid", "edit", "<input id = 'button1' type = 'button 'value = 'submit 'onclick = 'add () '/> <input id = 'button2' type = 'button' value = 'cancel 'onclick = 'cancel (\ "newid \") '/> ");
  58. }
  59. });
  60. });
  61. // Cancel the editing status
  62. Function cancel (ID ){
  63. If (ID = "newid") $ ("# Table1"). delrowdata ("newid ");
  64. Else $ ("# Table1"). restorerow (ID );
  65. }
  66. // Request new data from the background Ajax
  67. Function add (){
  68. VaR userid = $ ("# Table1"). Find ("# newid" + "_ userid"). Val ();
  69. VaR username = $ ("# Table1"). Find ("# newid" + "_ username"). Val ();
  70. VaR age = $ ("# Table1"). Find ("# newid" + "_ age"). Val ();
  71. VaR Tel = $ ("# Table1"). Find ("# newid" + "_ tel"). Val ();
  72. VaR email = $ ("# Table1"). Find ("# newid" + "_ email"). Val ();
  73. $. Ajax ({
  74. Type: "Post ",
  75. URL: "/home/Add ",
  76. Data: "userid =" + userid + "& username =" + username + "& age =" + age + "& Tel =" + Tel + "& Email =" + email,
  77. Success: function (MSG ){
  78. Alert ("add data:" + MSG );
  79. $ ("# Table1"). Trigger ("reloadgrid ");
  80. }
  81. });
  82. }
  83. // Send an Ajax request to the background to update the data
  84. Function Update (ID ){
  85. VaR userid = $ ("# Table1"). Find ("#" + ID + "_ userid"). Val ();
  86. VaR username = $ ("# Table1"). Find ("#" + ID + "_ username"). Val ();
  87. VaR age = $ ("# Table1"). Find ("#" + ID + "_ age"). Val ();
  88. VaR Tel = $ ("# Table1"). Find ("#" + ID + "_ tel"). Val ();
  89. VaR email = $ ("# Table1"). Find ("#" + ID + "_ email"). Val ();
  90. $. Ajax ({
  91. Type: "Post ",
  92. URL: "/home/update ",
  93. Data: "userid =" + userid + "& username =" + username + "& age =" + age + "& Tel =" + Tel + "& Email =" + email,
  94. Success: function (MSG ){
  95. Alert ("modify data:" + MSG );
  96. $ ("# Table1"). Trigger ("reloadgrid ");
  97. }
  98. });
  99. }
  100. // Request to delete data from the background Ajax
  101. Function Delete (ID ){
  102. VaR userid = $ ("# Table1"). getcell (ID, "userid ");
  103. $. Ajax ({
  104. Type: "Post ",
  105. URL: "/home/Delete ",
  106. Data: "userid =" + userid,
  107. Success: function (MSG ){
  108. Alert ("delete data:" + MSG );
  109. $ ("# Table1"). Trigger ("reloadgrid ");
  110. }
  111. });
  112. }

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:

 
 
  1. Public class homecontroller: Controller
  2. {
  3. Usermodel = new usermodel ();
  4. Public actionresult index ()
  5. {
  6. Return view ();
  7. }
  8. /// <Summary>
  9. /// Obtain the list of all users and provide the data to jqgrid through JSON
  10. /// </Summary>
  11. Public jsonresult userlist (string sord, string sidx, string rows, string page)
  12. {
  13. VaR list = usermodel. findall ();
  14. Int I = 0;
  15. VaR query = from u in list
  16. Select New
  17. {
  18. Id = I ++,
  19. Cell = new string [] {
  20. U ["userid"]. tostring (),
  21. U ["username"]. tostring (),
  22. U ["Age"]. tostring (),
  23. U ["tel"]. tostring (),
  24. U ["email"]. tostring (),
  25. "-"
  26. }
  27. };
  28. VaR DATA = new
  29. {
  30. Total = query. Count ()/convert. toint32 (rows) + 1,
  31. Page = convert. toint32 (PAGE ),
  32. Records = query. Count (),
  33. Rows = query. Skip (convert. toint32 (rows) * (convert. toint32 (PAGE)-1). Take (convert. toint32 (rows ))
  34. };
  35. Return JSON (data, jsonrequestbehavior. allowget );
  36. }
  37. /// <Summary>
  38. /// Respond to the JS "add" ajax request and perform the add user operation
  39. /// </Summary>
  40. Public contentresult add (string userid, string username, int age, string Tel, string email)
  41. {
  42. Document Doc = new document ();
  43. Doc ["userid"] = userid;
  44. Doc ["username"] = username;
  45. Doc ["Age"] = age;
  46. Doc ["tel"] = Tel;
  47. Doc ["email"] = Email;
  48. Try
  49. {
  50. Usermodel. Add (DOC );
  51. Return content ("added successfully ");
  52.  
  53. }
  54. Catch
  55. {
  56. Return content ("failed to add ");
  57. }
  58. }
  59. /// <Summary>
  60. /// Respond to the JS "delete" ajax request and perform the delete user operation
  61. /// </Summary>
  62. Public contentresult Delete (string userid)
  63. {
  64. Try
  65. {
  66. Usermodel. Delete (userid );
  67. Return content ("deleted successfully ");
  68. }
  69. Catch
  70. {
  71. Return content ("deletion failed ");
  72. }
  73. }
  74. /// <Summary>
  75. /// Respond to JS's "Update" ajax request and perform the update user operation
  76. /// </Summary>
  77. Public contentresult Update (string userid, string username, int age, string Tel, string email)
  78. {
  79. Document Doc = new document ();
  80. Doc ["userid"] = userid;
  81. Doc ["username"] = username;
  82. Doc ["Age"] = age;
  83. Doc ["tel"] = Tel;
  84. Doc ["email"] = Email;
  85. Try
  86. {
  87. Usermodel. Update (DOC );
  88. Return content ("modified successfully ");
  89. }
  90. Catch
  91. {
  92. Return content ("failed to modify ");
  93. }
  94. }
  95. }

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:

 
 
  1. Public class usermodel
  2. {
  3. // Link string (the three field values can be used as needed to read the configuration file)
  4. Public String connectionstring = "MongoDB: // localhost ";
  5. // Database Name
  6. Public String databasename = "mydatabase ";
  7. // Set Name
  8. Public String collectionname = "usercollection ";
  9. Private Mongo;
  10. Private relational database;
  11. Private collections <document> collections collection;
  12. Public usermodel ()
  13. {
  14. Mongo = new Mongo (connectionstring );
  15. Relational Database = Mongo. getdatabase (databasename) as relational database;
  16. Collect collection = collect database. getcollection <document> (collectionname) As collect collection <document>;
  17. Mongo. Connect ();
  18. }
  19. ~ Usermodel ()
  20. {
  21. Mongo. Disconnect ();
  22. }
  23. /// <Summary>
  24. /// Add a user record
  25. /// </Summary>
  26. /// <Param name = "Doc"> </param>
  27. Public void add (document DOC)
  28. {
  29. Collections collection. insert (DOC );
  30. }
  31. /// <Summary>
  32. /// Delete a user record
  33. /// </Summary>
  34. Public void Delete (string userid)
  35. {
  36. Collections collection. Remove (new document {"userid", userid }});
  37. }
  38. /// <Summary>
  39. /// Update a user record
  40. /// </Summary>
  41. /// <Param name = "Doc"> </param>
  42. Public void Update (document DOC)
  43. {
  44. Collections collection. findandmodify (Doc, new document {"userid", Doc ["userid"]. tostring ()}});
  45. }
  46. /// <Summary>
  47. /// Query all user records
  48. /// </Summary>
  49. /// <Returns> </returns>
  50. Public ienumerable <document> findall ()
  51. {
  52. Return response collection. findall (). Documents;
  53. }
  54. }

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.