MVC Application With MongoDB - Part 2

Please reference below link to understand how to connect to MongoDB server & create Database for our MVC application.

Please keep MongoDB server in running state while running MVC application.

Part-1 section include steps to start MongoDB server. Both command prompt need to be running ( mongod & mongo ).

Step 1: Create a new database.

  1. ObjectId id = new ObjectId();     
  2.     
  3. MongoClient client = null;     
  4. MongoServer server = null;     
  5. MongoDatabase database = null;     
  6. MongoCollection UserDetailscollection = null;     
  7.     
  8. string connectionString = "mongodb://localhost";     
  9. private List<UserModel> _UserList = new List<UserModel>();     
  10.     
  11. public UserRepositary()     
  12. {     
  13.     try    
  14.     {     
  15.         client = new MongoClient(connectionString);     
  16.     
  17.         server = client.GetServer();     
  18.     
  19.         database = server.GetDatabase("MVCDBTest");     
  20.              
  21.         UserDetailscollection = database.GetCollection<UserModel>("UserModel");     
  22.     }     
  23.     catch (Exception ex)     
  24.     {     
  25.         Console.WriteLine(ex.Message);     
  26.     }     
  27. }  
Firstly create MongoClient object. In this example we have MongoDB server installed on our machine so we pass local server connection string to MongoClient object. Using client object we get Server object.
  1. database = server.GetDatabase("MVCDBTest");   
Above line create database at MongoDB server.
  1. UserDetailscollection = database.GetCollection<UserModel>("UserModel");   
Above line create Collection inside MVCDBTest database. All data get inserted into this collection object as document.

The following commands are used to check database is created or not.

commands
  • show dbs – Display List of database available at server.

    If Database is created successfully, above command list down database name in command prompt.

  • use MVCDBTest

    We can switch to database now to check collection present in the current database.

  • show collections

    It lists down number of collection present into database. One database can have multiple collections present into it.

Step 2: UserModel Class.

In this class we are going to define attributes for our MVC application. MVC support data Annotation for validation purpose, so I added some validation for class attributes.

  1. using MongoDB.Bson;     
  2. using System;     
  3. using System.Collections.Generic;     
  4. using System.ComponentModel.DataAnnotations;     
  5. using System.Linq;     
  6. using System.Web;     
  7.     
  8. namespace MvcRegistration.Models     
  9. {     
  10.     public class UserModel     
  11.     {     
  12.         public ObjectId _id { getset; }     
  13.     
  14.         [Required(ErrorMessage = "Please enter your name.")]     
  15.         public string UserName { getset; }     
  16.     
  17.         [Required(ErrorMessage = "Please enter your password.")]     
  18.         [DataType(DataType.Password)]     
  19.         public string Password { getset; }     
  20.     
  21.         [Required(ErrorMessage = "Please enter your Email.")]     
  22.         [DataType(DataType.EmailAddress)]     
  23.         public string Email { getset; }     
  24.     
  25.         [Required(ErrorMessage = "Please enter your PhoneNo.")]     
  26.         public string PhoneNo { getset; }     
  27.     
  28.         [Required(ErrorMessage = "Please enter your Address.")]     
  29.         public string Address { getset; }     
  30.     }     
  31. }  
"Required" data Annotation indicate that this field is compulsory to enter to user otherwise MVC model return ModelState as invalid.
  1. public ObjectId _id { getset; }  
Each record of MongoDB is having unique id associated with it like primary key of table. So we need to declare attribute _id with data type as ObjectId.

Step 3: Dashboard Page ( index.cshtml ).

Dashboard

Application dashboard contain link to add New User. Below the link, database records are displayed in tabular format. Tabular format contain Edit & Delete button per record.

RouteConfig - Set starting point of application i.e Index method of UserController.
  1. public class RouteConfig     
  2. {     
  3.     public static void RegisterRoutes(RouteCollection routes)     
  4.     {     
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");     
  6.     
  7.         routes.MapRoute(     
  8.             name: "Default",     
  9.             url: "{controller}/{action}/{id}",     
  10.             defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }     
  11.         );     
  12.     }     
  13. }   
Index.cshtml
  1. @model IEnumerable<MvcRegistration.Models.UserModel>     
  2.     
  3. @{     
  4.     ViewBag.Title = "User DashBoard";     
  5. }     
  6.     
  7. <style type="text/css">     
  8.     table, tr {     
  9.         width:100%;     
  10.     }     
  11.     
  12.     th, td {     
  13.         width:20%;     
  14.     }     
  15.     th {     
  16.         background-color:yellow;            
  17.     }     
  18.     
  19.     td {     
  20.         background-color:aqua;            
  21.     }     
  22. </style>     
  23.          
  24. <h2>Index</h2>     
  25. <div>     
  26.     <div>     
  27.         @Html.ActionLink("Add User","Registration""User")     
  28.     </div>     
  29.     <div>     
  30.         @if (Model != null)     
  31.         {     
  32.             <table>     
  33.                 <thead>     
  34.                     <tr>     
  35.                         <th>User Name</th>     
  36.                         <th>Email</th>     
  37.                         <th>Address</th>     
  38.                         <th>PhoneNo</th>     
  39.                         <th>Object ID</th>     
  40.                         <th colspan="2">Action</th>     
  41.                     </tr>     
  42.                 </thead>     
  43.                 <tbody>     
  44.     
  45.                     @if (Model != null)     
  46.                     {     
  47.                         foreach (var UM in Model)     
  48.                         {     
  49.                         <tr>     
  50.                             <td>@UM.UserName</td>     
  51.                             <td>@UM.Email</td>     
  52.                             <td>@UM.Address</td>     
  53.                             <td>@UM.PhoneNo</td>     
  54.                             <td>@UM._id</td>     
  55.                             <td>     
  56.                                 <a href="@Url.Action("Edit", "User", new { ID = @UM.UserName})">Edit</a>     
  57.                                 <a onclick="return confirm('Are you sure about record Deletion ??');" href="@Url.Action("Delete", "User", new { ID = @UM.UserName })">Delete</a>     
  58.                             </td>     
  59.                         </tr>     
  60.                         }     
  61.                     }     
  62.     
  63.                 </tbody>     
  64.             </table>             
  65.         }     
  66.     </div>     
  67. </div>   
Controller Level code : Index() Method
  1. public ActionResult Index()     
  2. {     
  3.     return View("Index", Context.GetAllUsers());     
  4. }    
Step 4: Registration.cshtml.

Razor syntax is used to create view.

Registration

HTML helper classes are used to bind model with html tags.
  1. @Html.ValidationMessageFor(model => model.UserName)   
In order to show validation error message, the above syntax is used.
  1. using (Html.BeginForm("Registration""User"))   
It indicate which ActionResult method to execute after form submission.

Source Code
  1. @model MvcRegistration.Models.UserModel     
  2.     
  3. @{     
  4.     ViewBag.Title = "Registration";     
  5. }     
  6.     
  7. <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>     
  8. <script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>     
  9. <script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>     
  10.     
  11. <h2>Registration</h2>     
  12.     
  13. @using (Html.BeginForm("Registration""User"))     
  14. {     
  15.       
  16.     
  17.     <table>     
  18.         <tr>     
  19.             <td>@Html.LabelFor(model => model.UserName)</td>     
  20.             <td>@Html.TextBoxFor(model => model.UserName)</td>     
  21.             <td>@Html.ValidationMessageFor(model => model.UserName)</td>     
  22.         </tr>     
  23.         <tr>     
  24.             <td colspan="2"></td>     
  25.         </tr>     
  26.         <tr>     
  27.             <td>@Html.LabelFor(model => model.Password)</td>     
  28.             <td>@Html.PasswordFor(model => model.Password)</td>     
  29.             <td>@Html.ValidationMessageFor(model => model.Password)</td>     
  30.         </tr>     
  31.         <tr>     
  32.             <td colspan="2"></td>     
  33.         </tr>     
  34.         <tr>     
  35.             <td>@Html.LabelFor(model => model.Address)</td>     
  36.             <td>@Html.TextBoxFor(model => model.Address)</td>     
  37.             <td>@Html.ValidationMessageFor(model => model.Address)</td>     
  38.         </tr>     
  39.         <tr>     
  40.             <td colspan="2"></td>     
  41.         </tr>     
  42.         <tr>     
  43.             <td>@Html.LabelFor(model => model.Email)</td>     
  44.             <td>@Html.TextBoxFor(model => model.Email)</td>     
  45.             <td>@Html.ValidationMessageFor(model => model.Email)</td>     
  46.         </tr>     
  47.         <tr>     
  48.             <td colspan="2"></td>     
  49.         </tr>     
  50.         <tr>     
  51.             <td>@Html.LabelFor(model => model.PhoneNo)</td>     
  52.             <td>@Html.TextBoxFor(model => model.PhoneNo)</td>     
  53.             <td>@Html.ValidationMessageFor(model => model.PhoneNo)</td>     
  54.         </tr>     
  55.         <tr>     
  56.             <td colspan="2"></td>     
  57.         </tr>     
  58.         <tr>     
  59.             <td colspan="2">     
  60.                <input type="submit" value="Add" class="submitButton" />     
  61.             </td>     
  62.         </tr>     
  63.     </table>     
  64. }  
Controller Level code : Registration() Method
  1. public ActionResult Registration()     
  2. {     
  3.     return View();     
  4. }     
  5.     
  6. [HttpPost]     
  7. public ActionResult Registration(UserModel UM)     
  8. {     
  9.     if (ModelState.IsValid)     
  10.     {     
  11.         var result = Context.Add(UM);     
  12.     
  13.         return RedirectToAction("Index");     
  14.     }     
  15.     else    
  16.     {     
  17.         return RedirectToAction("Registration");     
  18.     }     
  19. }    
Example

index

Step 5: Edit User Details (Edit.cshtml).

Razor syntax is used to create view.

Edit User Details

Source Code
  1. @model MvcRegistration.Models.UserModel     
  2.     
  3. @{     
  4.     ViewBag.Title = "Edit";     
  5. }     
  6. <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>     
  7. <script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>     
  8. <script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>     
  9. <h2>Edit</h2>     
  10. @using (Html.BeginForm("Edit""User"))     
  11. {     
  12.     @Html.ValidationSummary(true)     
  13.     
  14.     <table>     
  15.         <tr>     
  16.             <td>@Html.LabelFor(model => model.UserName)</td>     
  17.             <td>@Html.TextBoxFor(model => model.UserName, new { @readonly="readonly"})</td>     
  18.             <td>@Html.ValidationMessageFor(model => model.UserName)</td>     
  19.         </tr>     
  20.         <tr>     
  21.             <td colspan="2"></td>     
  22.         </tr>     
  23.          <tr>     
  24.             <td>@Html.LabelFor(model => model.Password)</td>     
  25.             <td>@Html.PasswordFor(model => model.Password, new { value= Model.Password })</td>     
  26.             <td>@Html.ValidationMessageFor(model => model.Password)</td>     
  27.         </tr>     
  28.         <tr>     
  29.             <td colspan="2"></td>     
  30.         </tr>     
  31.         <tr>     
  32.             <td>@Html.LabelFor(model => model.Address)</td>     
  33.             <td>@Html.TextBoxFor(model => model.Address)</td>     
  34.             <td>@Html.ValidationMessageFor(model => model.Address)</td>     
  35.         </tr>     
  36.         <tr>     
  37.             <td colspan="2"></td>     
  38.         </tr>     
  39.         <tr>     
  40.             <td>@Html.LabelFor(model => model.Email)</td>     
  41.             <td>@Html.TextBoxFor(model => model.Email)</td>     
  42.             <td>@Html.ValidationMessageFor(model => model.Email)</td>     
  43.         </tr>     
  44.         <tr>     
  45.             <td colspan="2"></td>     
  46.         </tr>     
  47.         <tr>     
  48.             <td>@Html.LabelFor(model => model.PhoneNo)</td>     
  49.             <td>@Html.TextBoxFor(model => model.PhoneNo)</td>     
  50.             <td>@Html.ValidationMessageFor(model => model.PhoneNo)</td>     
  51.         </tr>     
  52.         <tr>     
  53.             <td colspan="2"></td>     
  54.         </tr>     
  55.         <tr>     
  56.             <td colspan="2">     
  57.                <input type="submit" value="Save" class="submitButton" />     
  58.             </td>     
  59.         </tr>     
  60.     </table>     
  61. }    
Explanation
  1. @using (Html.BeginForm("Edit""User"))   
Indicate which method to execute on form submission.
  1. @Html.TextBoxFor(model => model.UserName, new { @readonly="readonly"})   
UserName is readonly field so it is done using the following code.
  1. @Html.PasswordFor(model => model.Password, new { value= Model.Password })   
We want to set value to password field so the following code is used.

Controller Level code : Edit() Method
  1. public ActionResult Edit(string id)     
  2. {     
  3.     var User = Context.GetUserByID(id);     
  4.     
  5.     return View(User);     
  6. }     
  7.     
  8. [HttpPost]     
  9. public ActionResult Edit(UserModel UM)     
  10. {     
  11.     if (ModelState.IsValid)     
  12.     {     
  13.         Context.Update(UM.UserName, UM);     
  14.     
  15.         return RedirectToAction("Index");     
  16.     }     
  17.     else    
  18.     {     
  19.         return RedirectToAction("Edit");     
  20.     }                 
  21. }    
Step 6: Record Deletion.

Index.cshtml code - The following code call delete method of UserController which has logic to delete user record.
  1. <a onclick="return confirm('Are you sure about record Deletion ??');"href="@Url.Action("Delete", "User", new { ID = @UM.UserName })">Delete</a>  
Record Deletion

Controller Level code : Delete() Method
  1. public ActionResult Delete(string id)     
  2. {     
  3.     Context.Delete(id);     
  4.     return RedirectToAction("Index");     
  5. }  
Step 7: Controller Code
  1. using System;     
  2. using System.Collections.Generic;     
  3. using System.Linq;     
  4. using System.Web;     
  5. using System.Web.Mvc;     
  6. using System.Data.Entity;     
  7. using System.Data.SqlClient;     
  8.     
  9. using MongoDB.Bson;     
  10. using MongoDB.Driver;     
  11. using MongoDB.Driver.Linq;     
  12. using MvcRegistration.Models;     
  13. using MongoDB.Driver.Builders;     
  14.     
  15. namespace MvcRegistration.Controllers     
  16. {     
  17.     public class UserController : Controller     
  18.     {     
  19.         public UserRepositary Context = new UserRepositary();     
  20.         
  21.         public ActionResult Index()     
  22.         {     
  23.             return View("Index", Context.GetAllUsers());     
  24.         }     
  25.     
  26.         public ActionResult Registration()     
  27.         {     
  28.             return View();     
  29.         }     
  30.     
  31.         [HttpPost]     
  32.         public ActionResult Registration(UserModel UM)     
  33.         {     
  34.             if (ModelState.IsValid)     
  35.             {     
  36.                 var result = Context.Add(UM);     
  37.     
  38.                 return RedirectToAction("Index");     
  39.             }     
  40.             else    
  41.             {     
  42.                 return RedirectToAction("Registration");     
  43.             }     
  44.         }     
  45.     
  46.         public ActionResult Edit(string id)     
  47.         {     
  48.             var User = Context.GetUserByID(id);     
  49.     
  50.             return View(User);     
  51.         }     
  52.     
  53.         [HttpPost]     
  54.         public ActionResult Edit(UserModel UM)     
  55.         {     
  56.             if (ModelState.IsValid)     
  57.             {     
  58.                 Context.Update(UM.UserName, UM);     
  59.     
  60.                 return RedirectToAction("Index");     
  61.             }     
  62.             else    
  63.             {     
  64.                 return RedirectToAction("Edit");     
  65.             }                 
  66.         }     
  67.     
  68.         public ActionResult Delete(string id)     
  69.         {     
  70.             Context.Delete(id);     
  71.             return RedirectToAction("Index");     
  72.         }     
  73.     }     
  74. }   
Step 8: UserRepositary.cs
  1. using MongoDB.Bson;     
  2. using MongoDB.Driver;     
  3. using MongoDB.Driver.Builders;     
  4. using System;     
  5. using System.Collections.Generic;     
  6. using System.Linq;     
  7. using System.Web;     
  8.     
  9. namespace MvcRegistration.Models     
  10. {     
  11.     public class UserRepositary : IUserRepositary     
  12.     {     
  13.         ObjectId id = new ObjectId();     
  14.     
  15.         MongoClient client = null;     
  16.         MongoServer server = null;     
  17.         MongoDatabase database = null;     
  18.         MongoCollection UserDetailscollection = null;     
  19.     
  20.         string connectionString = "mongodb://localhost";     
  21.         private List<UserModel> _UserList = new List<UserModel>();     
  22.     
  23.         public UserRepositary()     
  24.         {     
  25.             try    
  26.             {     
  27.                 client = new MongoClient(connectionString);     
  28.     
  29.                 server = client.GetServer();     
  30.     
  31.                 database = server.GetDatabase("MVCDBTest");     
  32.                      
  33.                 UserDetailscollection = database.GetCollection<UserModel>("UserModel");     
  34.             }     
  35.             catch (Exception ex)     
  36.             {     
  37.                 Console.WriteLine(ex.Message);     
  38.             }     
  39.         }     
  40.     
  41.         public IEnumerable<UserModel> GetAllUsers()     
  42.         {     
  43.             if (Convert.ToInt32(UserDetailscollection.Count()) > 0)     
  44.             {     
  45.                 _UserList.Clear();     
  46.     
  47.                 var AllUsers = UserDetailscollection.FindAs(typeof(UserModel), Query.NE("UserName""null"));     
  48.     
  49.                 if (AllUsers.Count() > 0)     
  50.                 {     
  51.                     foreach (UserModel user in AllUsers)     
  52.                     {     
  53.                         _UserList.Add(user);     
  54.                     }     
  55.                 }                    
  56.             }     
  57.     
  58.             var result = _UserList.AsQueryable();     
  59.             return result;     
  60.         }     
  61.     
  62.         public UserModel Add(UserModel UM)     
  63.         {     
  64.             UserDetailscollection.Save(UM);     
  65.                  
  66.             return UM;     
  67.         }     
  68.     
  69.         public UserModel GetUserByID(string id)     
  70.         {     
  71.             UserModel SearchUser = null;     
  72.     
  73.             if (!string.IsNullOrEmpty(id))     
  74.             {     
  75.                 SearchUser = (UserModel)UserDetailscollection.FindOneAs(typeof(UserModel), Query.EQ("UserName", id));     
  76.             }     
  77.     
  78.             return SearchUser;     
  79.         }     
  80.     
  81.         public bool Update(string objectid, UserModel UM)     
  82.         {     
  83.             UpdateBuilder upBuilder = MongoDB.Driver.Builders.Update     
  84.                 .Set("UserName", UM.UserName)     
  85.                 .Set("Password", UM.Password)     
  86.                 .Set("Address", UM.Address)     
  87.                 .Set("Email", UM.Email)     
  88.                 .Set("PhoneNo", UM.PhoneNo);     
  89.     
  90.             UserDetailscollection.Update(Query.EQ("UserName",objectid), upBuilder);     
  91.     
  92.             return true;     
  93.         }     
  94.     
  95.         public bool Delete(string objectid)     
  96.         {     
  97.             UserDetailscollection.Remove(Query.EQ("UserName", objectid));     
  98.             return true;     
  99.         }     
  100.     }     
  101. }   
Output

Output

I hope it is useful to all the readers of C# corner like my previous articles on this series