CRUD Operations Using ASP.NET MVC and MongoDB

In this article, we will learn how to perform CRUD operations using ASP.NET MVC and MongoDB. In my previous articles, I explained the  basic functions of MongoDB that are required to insert, update, and delete the data. The purpose of this series of articles is to learn how we use MongoDB with .NET applications. In the last few articles, we have learned MongoDB with C# Console applications. You can check my previous articles here -

You can check how to set up the MongoDB environment from Here.

Step for CRUD Operation

Step 1

Open Visual Studio and create a new project.
 
CRUD Operations Using ASP.NET MVC and MongoDB 
 
Name it as CrudOperation_MvcandMongoDB.
 
CRUD Operations Using ASP.NET MVC and MongoDB 

Choose the Template tpe as MVC.

CRUD Operations Using ASP.NET MVC and MongoDB 

Step 2

Add MongoDB Drivers for C# using NuGet Package Manager.
 
CRUD Operations Using ASP.NET MVC and MongoDB 
 
Add the required Namespace for MongoDB.
  1. using MongoDB.Driver;      
  2. using MongoDB.Bson;    

Step 3

Now, add a connection string in the web.config file and add the follwoing line in the App Settings section of that file.
  1. <add key="connectionString" value="mongodb://localhost"/>  

Step 4

Add a class in Models folder and name it EmployeeDetails.
 
CRUD Operations Using ASP.NET MVC and MongoDB 

Now, add the following lines.

  1. public String Id { getset; }  
  2. public string Name { getset; }  
  3. public string Department { getset; }  
  4. public string Address { getset; }  
  5. public string City { getset; }  
  6. public string Country { getset; }  

Step 5

Click on Controller Folder and add a new empty controller and name it Home Controller
 
CRUD Operations Using ASP.NET MVC and MongoDB 

Step 6

Now add a Connection string in Web.config File and Web.config and add the follwoing line in App settings section. Now Add using System.Configuration in Controller and add an actionmethod to insert data into the database. Add the following Namespace to import Model.
  1. using CrudOperation_MvcandMonGoDB.Models;  

Add these lines in the action method to insert data into database

  1. [HttpPost]  
  2. public ActionResult Index(EmployeeDetails Emp)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         string constr = ConfigurationManager.AppSettings["connectionString"];  
  7.         var Client = new MongoClient(constr);  
  8.         var DB = Client.GetDatabase("Employee");  
  9.         var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails");  
  10.         collection.InsertOneAsync(Emp);  
  11.         return RedirectToAction("emplist");  
  12.     }  
  13.     return View();  
  14. }  

Now click on the index method and add a view and add the following code in the View.

  1. @model CrudOperation_MvcandMonGoDB.Models.EmployeeDetails    
  2.     
  3. <div class="col-md-12">    
  4.     <h2>Employee Detail</h2>    
  5. </div>    
  6.     
  7. @using (Html.BeginForm())     
  8. {    
  9.     @Html.AntiForgeryToken()    
  10.         
  11.     <div class="form-horizontal">    
  12.             
  13.     <hr />    
  14.     <div class="form-group">    
  15.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })    
  16.             <div class="col-md-10">    
  17.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })    
  18.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })    
  19.             </div>    
  20.         </div>    
  21.     
  22.         <div class="form-group">    
  23.             @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })    
  24.             <div class="col-md-10">    
  25.                 @Html.EditorFor(model => model.Department, new { htmlAttributes = new { @class = "form-control" } })    
  26.                 @Html.ValidationMessageFor(model => model.Department, ""new { @class = "text-danger" })    
  27.             </div>    
  28.         </div>    
  29.     
  30.         <div class="form-group">    
  31.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })    
  32.             <div class="col-md-10">    
  33.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })    
  34.                 @Html.ValidationMessageFor(model => model.Address, ""new { @class = "text-danger" })    
  35.             </div>    
  36.         </div>    
  37.     
  38.         <div class="form-group">    
  39.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })    
  40.             <div class="col-md-10">    
  41.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })    
  42.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })    
  43.             </div>    
  44.         </div>    
  45.     
  46.         <div class="form-group">    
  47.             @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })    
  48.             <div class="col-md-10">    
  49.                 @Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })    
  50.                 @Html.ValidationMessageFor(model => model.Country, ""new { @class = "text-danger" })    
  51.             </div>    
  52.         </div>    
  53.     
  54.         <div class="form-group">    
  55.             <div class="col-md-offset-2 col-md-10">    
  56.                 <input type="submit" value="Add" class="btn btn-primary" />    
  57.             </div>    
  58.         </div>    
  59.     </div>    
  60. }    
  61. @section Scripts {    
  62.     @Scripts.Render("~/bundles/jqueryval")    
  63. } 

Run the Project and try to insert data

CRUD Operations Using ASP.NET MVC and MongoDB 

Now open Robo 3T and check the data is inserted

CRUD Operations Using ASP.NET MVC and MongoDB 

Record is successfully inserted into the database

Step 7

Now we retrieve data from the database. Add an Actionmethod and add the following code to retrieve data from the database.
  1. public ActionResult emplist()    
  2. {    
  3.     string constr = ConfigurationManager.AppSettings["connectionString"];    
  4.     var Client = new MongoClient(constr);    
  5.     var db = Client.GetDatabase("Employee");    
  6.     var collection = db.GetCollection<EmployeeDetails>("EmployeeDetails").Find(new BsonDocument()).ToList();    
  7.                
  8.     return View(collection);    
  9. }    

Now add a view to display data and add the following code.

  1. @model IEnumerable<CrudOperation_MvcandMonGoDB.Models.EmployeeDetails>    
  2.     
  3. @{    
  4.     ViewBag.Title = "Employee Details";    
  5. }    
  6.     
  7. <h3 style="text-align:center">Employee Details</h3>    
  8.     
  9. <p>    
  10.     @Html.ActionLink("Add New Employee""Index")    
  11. </p>    
  12. <table class="table">    
  13.     <tr>    
  14.         <th>    
  15.             @Html.DisplayNameFor(model => model.Name)    
  16.         </th>    
  17.         <th>    
  18.             @Html.DisplayNameFor(model => model.Department)    
  19.         </th>    
  20.         <th>    
  21.             @Html.DisplayNameFor(model => model.Address)    
  22.         </th>    
  23.         <th>    
  24.             @Html.DisplayNameFor(model => model.City)    
  25.         </th>    
  26.         <th>    
  27.             @Html.DisplayNameFor(model => model.Country)    
  28.         </th>    
  29.         <th></th>    
  30.     </tr>    
  31.     
  32. @foreach (var item in Model) {    
  33.     <tr>    
  34.         <td>    
  35.             @Html.DisplayFor(modelItem => item.Name)    
  36.         </td>    
  37.         <td>    
  38.             @Html.DisplayFor(modelItem => item.Department)    
  39.         </td>    
  40.         <td>    
  41.             @Html.DisplayFor(modelItem => item.Address)    
  42.         </td>    
  43.         <td>    
  44.             @Html.DisplayFor(modelItem => item.City)    
  45.         </td>    
  46.         <td>    
  47.             @Html.DisplayFor(modelItem => item.Country)    
  48.         </td>    
  49.         <td>    
  50.            @Html.ActionLink("Edit""Edit"new { id=item.Id }) |    
  51.                
  52.             @Html.ActionLink("Delete""Delete"new { id=item.Id })    
  53.         </td>    
  54.     </tr>    
  55. }    
  56.     
  57. </table>   
Run the Project
 
CRUD Operations Using ASP.NET MVC and MongoDB 

Step 8

Add a new Method for deleting data based on Id and add the following code to delete data
  1. public ActionResult Delete(string id)    
  2. {    
  3.     if (ModelState.IsValid)    
  4.     {    
  5.         string constr = ConfigurationManager.AppSettings["connectionString"];    
  6.         var Client = new MongoClient(constr);    
  7.         var DB = Client.GetDatabase("Employee");    
  8.         var collection = DB.GetCollection<EmployeeDetails>("EmployeeDetails");    
  9.         var DeleteRecored = collection.DeleteOneAsync(    
  10.                        Builders<EmployeeDetails>.Filter.Eq("Id", id));    
  11.         return RedirectToAction("emplist");    
  12.     }    
  13.     return View();    
  14.   
  15. } 

Step 9

For editing data add Actionmethod and add code for editing data.
  1. public ActionResult Edit(EmployeeDetails Empdet)    
  2. {    
  3.     if (ModelState.IsValid)    
  4.     {    
  5.         string constr = ConfigurationManager.AppSettings["connectionString"];    
  6.         var Client = new MongoClient(constr);    
  7.         var Db = Client.GetDatabase("Employee");    
  8.         var collection = Db.GetCollection<EmployeeDetails>("EmployeeDetails");    
  9.           
  10.         var update = collection.FindOneAndUpdateAsync(Builders<EmployeeDetails>.Filter.Eq("Id", Empdet.Id), Builders<EmployeeDetails>.Update.Set("Name", Empdet.Name).Set("Department", Empdet.Department).Set("Address", Empdet.Address).Set("City", Empdet.City).Set("Country", Empdet.Country));    
  11.   
  12.         return RedirectToAction("emplist");    
  13.     }    
  14.     return View();    
  15. } 

Now add a view

  1. @model CrudOperation_MvcandMonGoDB.Models.EmployeeDetails    
  2.     
  3. @{    
  4.     ViewBag.Title = "Edit";    
  5. }    
  6.     
  7. <h2>Edit</h2>    
  8.     
  9. @using (Html.BeginForm())    
  10. {    
  11.     @Html.AntiForgeryToken()    
  12.         
  13.     <div class="form-horizontal">    
  14.         <h4>EmployeeDetails</h4>    
  15.         <hr />    
  16.         @Html.ValidationSummary(true""new { @class = "text-danger" })    
  17.         @Html.HiddenFor(model => model.Id)    
  18.     
  19.         <div class="form-group">    
  20.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })    
  21.             <div class="col-md-10">    
  22.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })    
  23.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })    
  24.             </div>    
  25.         </div>    
  26.     
  27.         <div class="form-group">    
  28.             @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })    
  29.             <div class="col-md-10">    
  30.                 @Html.EditorFor(model => model.Department, new { htmlAttributes = new { @class = "form-control" } })    
  31.                 @Html.ValidationMessageFor(model => model.Department, ""new { @class = "text-danger" })    
  32.             </div>    
  33.         </div>    
  34.     
  35.         <div class="form-group">    
  36.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })    
  37.             <div class="col-md-10">    
  38.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })    
  39.                 @Html.ValidationMessageFor(model => model.Address, ""new { @class = "text-danger" })    
  40.             </div>    
  41.         </div>    
  42.     
  43.         <div class="form-group">    
  44.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })    
  45.             <div class="col-md-10">    
  46.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })    
  47.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })    
  48.             </div>    
  49.         </div>    
  50.     
  51.         <div class="form-group">    
  52.             @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })    
  53.             <div class="col-md-10">    
  54.                 @Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })    
  55.                 @Html.ValidationMessageFor(model => model.Country, ""new { @class = "text-danger" })    
  56.             </div>    
  57.         </div>    
  58.     
  59.         <div class="form-group">    
  60.             <div class="col-md-offset-2 col-md-10">    
  61.                 <input type="submit" value="Save" class="btn btn-default" />    
  62.             </div>    
  63.         </div>    
  64.     </div>    
  65. }    
  66.     
  67. <div>    
  68.     @Html.ActionLink("Back to List""Index")    
  69. </div> 

Now we run the project.

Summary
 
In this article, we learned about Crud operations using Asp.net MVC and MongoDB. This article gives you a basic understanding of how we can use MongoDB with Asp.net MVC applications. In the next article, we will learn registration and logging in using Asp.net MVC and MongoDB. 


Similar Articles