Simple CRUD Operation Using ASP.NET MVC And MongoDB

Use this link for downloading the project.

In this article, we are going to learn how to perform simple CRUD operations using ASP.NET MVC and MongoDB. If you are new to MongoDB and want to know the basics, then just click on the below link to kick start your tour with Mongo.

Most people nowadays want to use open source products available in the market. Here is yet another product called MongoDB which is a No SQL database that stores data in JSON object format and also calls a BSON document.

Many people might think that it is open source database and we cannot use this kind of database with .NET applications. But, I say that we can use this database with.NET too. That is good news, right ?

MongoDB provides a driver called mongocsharp driver which we need to download and install from NuGet Package Manager into application to connect to MongoDB database. It is simple to use, and finally we are going to perform simple CRUD operation which will give a basic idea of how to use this database, how data is stored, and how we can pull data from the database as per our needs.

Before starting, let’s have a look at the topics.

Topic

  1. Create MVC Application
  2. Adding mongocsharp driver form NuGet Package
  3. Connecting to MongoDB database.
  4. Setting connecting string.
  5. Adding Model
  6. Adding Controller CarinformationController
  7. Performing CRUD operation
  8. CREATE
  9. READ (Single / Multiple) Document
  10. EDIT / UPDATE
  11. DELETE

Let’s begin our journey to learn simple CRUD operation with ASP.NET MVC using MongoDB.

Create MVC application

Open Visual Studio IDE and click on "New Project" link. A "New Project" dialog will pop up.


Inside that, from left pane choose templates ➜ choose Visual C# ➜ Web template. Then, in the middle pane, you will see the list of ASP.NET Web Application templates. Select ASP.NET Web Application (.NET Framework)" project templates.


Enter the project name “MongoDemo” and finally click on the OK button.

After that, a new dialog will pop up with name “New ASP.NET Web Application”. In this, we are going to choose MVC project template and click on OK button for creating a project.


Below is complete project view which is newly created


After creating a new project, in the next step, we are going to add a mongocsharp driver to the project.

Adding mongocsharp driver form NuGet Package

To add mongocsharp driver, just right click on the project and from the list of menu, choose "Manage NuGet Package".


A new dialog will pop up where we are going to choose Browse tab. In search box, type “mongocsharp driver”  which will show a list of other NuGet packages. Select the first one and click on "Install" button to install it in the project.


After installing, you can see project reference where you will find MongoDB driver reference too.


Now, we have installed “mongocsharp driver” successfully. Now, we are going to connect to MongoDB database.

Connecting to MongoDB database

In this step, we are going to connect MVC application with MongoDB database.

Starting MongoDB Server

 In this part, we are going to start MongoDB Server.


Starting MongoDB Client

In this part, we are going to start MongoDB Client.


After starting the Server and client, next we are going to create database.

Creating a New Database in MongoDB

In this part, we are going to creating the database first with name “CarDatabase”.

After we have created database next step we are going to set credentials for this database such that application having valid credentials can only access this database.

Database credentials

Username: - demouser

Password: -Pass@123

Below is snapshot of how to set credentials to database


After adding the database and setting the credentials for the database next we are going create a context class for central accessing MongoDB database settings.

Setting Connecting string

In this part we are going create a class with name MongoContext in App_Start folder.


After creating class next we are going to set all credentials in Web.config appSettings sections.

It is easy to update any setting in the future if some details have changed.  Now we need to deploy the code  --  just a change in the Web.config file and it is done.

Below is snapshot of appSettings


Code Snippet 

  1. <appSettings>      
  2. <add key="MongoDatabaseName" value="CarDatabase" />  
  3. <add key="MongoUsername" value="demouser" />  
  4. <add key="MongoPassword" value="Pass@123" />  
  5. <add key="MongoPort" value="27017" />  
  6. <add key="MongoHost" value="localhost" />  
  7. </appSettings>   

After finishing with appSettings next we are going read this value in MongoContext class.

MongoContext Class Code snippet


In this class first we have declared 3 variables

  1. MongoClient
  2. MongoServer
  3. MongoDatabase

Then in the constructor of the class, we are getting values of Mongo Database from appSettings which we have set. Next we are passing these values to [MongoCredential.CreateMongoCRCredential] method for creating MongoCredential, and then in the next step, we are setting MongoClientSettings, for this setting we need to pass MongoCredential; along with that, we need to pass Host name and Port number of MongoDB.

Code Snippet 

  1. using MongoDB.Driver;  
  2. using System;  
  3. using System.Configuration;  
  4.   
  5. namespace MongoDemo.App_Start  
  6. {  
  7.     public class MongoContext  
  8.     {  
  9.         MongoClient _client;  
  10.         MongoServer _server;  
  11.         public MongoDatabase _database;  
  12.         public MongoContext()        //constructor   
  13.         {  
  14.             // Reading credentials from Web.config file   
  15.             var MongoDatabaseName = ConfigurationManager.AppSettings["MongoDatabaseName"]; //CarDatabase  
  16.             var MongoUsername = ConfigurationManager.AppSettings["MongoUsername"]; //demouser  
  17.             var MongoPassword = ConfigurationManager.AppSettings["MongoPassword"]; //Pass@123  
  18.             var MongoPort = ConfigurationManager.AppSettings["MongoPort"];  //27017  
  19.             var MongoHost = ConfigurationManager.AppSettings["MongoHost"];  //localhost  
  20.   
  21.             // Creating credentials  
  22.             var credential = MongoCredential.CreateMongoCRCredential  
  23.                             (MongoDatabaseName,  
  24.                              MongoUsername,  
  25.                              MongoPassword);  
  26.   
  27.             // Creating MongoClientSettings  
  28.             var settings = new MongoClientSettings  
  29.             {  
  30.                 Credentials = new[] { credential },  
  31.                 Server = new MongoServerAddress(MongoHost, Convert.ToInt32(MongoPort))    
  32.             };  
  33.             _client = new MongoClient(settings);  
  34.             _server = _client.GetServer();  
  35.             _database = _server.GetDatabase(MongoDatabaseName);  
  36.         }  
  37.     }  
  38. }   

After we have completed with setting up connecting string in the next step we are going to adding Model which is going to be table.

Adding Model

In this part we are going to add a model (a class) in Models folder with name “CarModel”, and properties inside CarModel are decorated with MongoDB attribute.

Note

Attributes used to control Bson serialization/deserialization.


After adding model next we are going add a controller with name CarinformationController.

Adding Controller

For adding controller just right click on controller folder and choose add menu and inside that choose controller menu a new dialog pop up with name “Add scaffold” in this just choose “MVC 5 Controller with read/write actions” and click on add button.


After clicking on Add button a new dialog will pop up with name “Add Controller” and it is going to ask for Controller name and we are going to name Controller as CarinformationController and finally, click on Add button to add a controller.


After clicking on add button it is going to create CarinformationController and along with it is also going to add default action method [Create, Index, Edit, Delete, and Details] as shown in below snapshot.


After adding controller the first thing we are going to work on is to add a constructor to Controller for initializing MongoDB objects.


Code snippet 

  1. MongoContext _dbContext;  
  2. public CarinformationController()  
  3. {  
  4.     _dbContext = new MongoContext();  
  5. }   

After initializing MongoDB objects next we are going to start performing CRUD operation.

CREATE

After adding Constructor next we are going to edit Create Action Method for adding “Create” View to take input.


For adding view just right click inside Create Action Method and choose Add View from the list of the menu. After choosing that a new dialog will pop up with name Add View in this dialog just choose template “Create” and Model class as “CarModel” click on Add button.


After adding view below is snapshot of code view and browser view of “Create” View


Now let’s write code to insert data in the database.

In this part we are going to insert data into database, and for doing that first we need to create MongoCollection object.

Code Snippet

  1. var document = _dbContext._database.GetCollection<BsonDocument>("CarModel");   

In the next step, we have added a filter to check duplication of the document. 

  1. var query = Query.And(Query.EQ("Carname", carmodel.Carname), Query.EQ("Color", carmodel.Color));  
  2.   
  3. var count = document.FindAs<CarModel>(query).Count();  
  4.   
  5.   if (count == 0)  
  6.   {  
  7.     var result = document.Insert(carmodel);  
  8.   }  
  9.   else  
  10.   {  
  11.     TempData["Message"] = "Carname ALready Exist";  
  12.     return View("Create", carmodel);  
  13.   }   

Passing Model to insert data after check

 

  1. var result = document.Insert(carmodel);  

 

Snapshot of Create ActionMethod


Now let’s save the code and run the application.

After running the application just access URL - http://localhost:####/Carinformation/Create

After accessing it a create view will appear as shown in the below snapshot.


Fill details of form and click on submit button to save data in MongoDB database (“CarDatabase”).

After clicking on insert button data is inserted into (“CarDatabase”) and we get response ok as 1.


Wow, we have to insert the first document into MongoDB database. Next we are going to Read data from inserted data.

READ [Multiple Document]

In this part, we are going to display records in a Grid format which we have saved in MongoDB database.

For displaying all records we are going to use FindAll() method of MongoDB as shown in below snapshot.

Snapshot of Index ActionMethod


Code Snippet 

  1. public ActionResult Index()  
  2. {  
  3.   var carDetails = _dbContext._database.GetCollection<CarModel>("CarModel").FindAll().ToList();  
  4.   return View(carDetails);  
  5. }   

Now let’s add Index View.

For adding Index View just right click inside Index Action Method and choose Add View from the list of the menu after choosing a new dialog will pop up with name Add View in this dialog just choose template “List” and Model class as “CarModel” click on Add button.


Below is a snapshot of Index View which is generated.


Now let’s save code and run the application.

After running application just access URL: - http://localhost:####/Carinformation/Index

After accessing an Index View will appear as shown in below snapshot.

This View will contain data which we have inserted.


Wow, we have pulled data from MongoDB database.

But we have not configured the link in this part, so let’s configure it.


We have assigned object id which is a unique id in MongoDB to id parameter in ActionLink.


READ [Single Document]

In this part, we are going to display single records (Details) according to ObjectId which we choose from index View.

For displaying single records (Details) we are going to use FindOne() method as shown in the below snapshot.

Snapshot of Details ActionMethod


After completing the code snippet now let’s add Details View.

For adding view just right click inside Details Action Method and choose Add View from the list of the menu. After choosing this a new dialog will pop up with name Add View. In this dialog just choose template “Details” and Model class as “CarModel” click on Add button.


Below is a snapshot of Details View which is generated.


Now let’s save the code and run the application.

After running the application just access URL - http://localhost:####/Carinformation/Index

After accessing an Index view will appear as shown in below snapshot.

Then we are going to click on Details button to see Details View.


After clicking on Details button it will call Details Action Method which takes Objectid as input parameter and on basis of that parameter it gets data from MongoDB database to display data.

Details View


After completing with Details View in next part we are going to edit Car record.

EDIT / UPDATE

In this part, we are going to edit records which we have saved in MongoDB database.

For editing records first, we need to get that data from the database to display it; after that we can update the data.

In the below snapshot we are first validating if the document already exists in the database or not by passing ObjectId and getting a count of the document if the count of the document is greater than 0 then the document exists after that we only get data for displaying in Edit mode.

Snapshot of Edit ActionMethod


Code Snippet 

  1. // GET: Carinformation/Edit/5  
  2.         public ActionResult Edit(string id)  
  3.         {  
  4.             var document = _dbContext._database.GetCollection<CarModel>("CarModel");  
  5.   
  6.             var carDetailscount = document.FindAs<CarModel>(Query.EQ("_id"new ObjectId(id))).Count();  
  7.   
  8.             if (carDetailscount > 0)  
  9.             {  
  10.                 var carObjectid = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));  
  11.   
  12.                 var carDetail = _dbContext._database.GetCollection<CarModel>("CarModel").FindOne(carObjectid);  
  13.   
  14.                 return View(carDetail);  
  15.             }  
  16.             return RedirectToAction("Index");  
  17.         }   

Now let’s add Edit View.

For adding view just right click inside Edit Action Method and choose Add View from the list of the menu. After choosing it a new dialog will pop up with the name Add View --  in this dialog just choose template “Edit” and Model class as “CarModel” click on Add button.


Below is a snapshot of Edit View which is generated.


Now let’s save code and run the application.

After running application just access URL: - http://localhost:####/Carinformation/Index

After accessing an Index view will appear as shown in below snapshot.

Then we are going to click on Edit button to see Edit View.


Now we have just shown data in edit mode now we need to write code for updating these values to MongoDB database on click of save button. For that, we are going to add another Action Method with same name Edit which will handle [HttpPost] Request.

Update

Snapshot of Edit ActionMethod


Code Snippet 

  1. // POST: Carinformation/Edit/5  
  2.         [HttpPost]  
  3.         public ActionResult Edit(string id, CarModel carmodel)  
  4.         {  
  5.             try  
  6.             {  
  7.                 carmodel.Id = new ObjectId(id);  
  8.                 //Mongo Query  
  9.                 var CarObjectId = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));  
  10.                 // Document Collections  
  11.                 var collection = _dbContext._database.GetCollection<CarModel>("CarModel");  
  12.                 // Document Update which need Id and Data to Update  
  13.                 var result = collection.Update(CarObjectId, Update.Replace(carmodel), UpdateFlags.None);  
  14.                 return RedirectToAction("Index");  
  15.             }  
  16.             catch  
  17.             {  
  18.                 return View();  
  19.             }  
  20.         }   

Now let’s save code and run the application.

After running application just access URL - http://localhost:####/Carinformation/Index

After accessing it, an Index view will appear as shown in the below snapshot.

Then we are going to click on Edit button to see Edit View.


After clicking on Edit button you can see Edit view in Edit Mode. Now in this Mode we are going to update the Color of the Car from Blue to Brown and click on “Save” button to update values.


After clicking on update button this value gets updated in the database and it is redirected to the index page for displaying grid.

Now if we see index view then update value will be displayed.


Wow, we have completed with Updating data in MongoDB.

DELETE

In this part, we are going to delete the record which we have saved in MongoDB database.

For delete records first, we need to get that data from the database to display, and after that we can delete data.

Snapshot of Delete ActionMethod


Now in this process we are first going to open index view from there we are going to click on Delete button then delete action method will get called which take Objectid as input parameter and then we are going to pass this parameter to create mongo query then this query will be passed to GetCollection method to get Car model data.

After adding Action method with name delete which handles HttpGet request now let’s add Delete View to display record to delete.

Now let’s add Delete View.

For adding view just right click inside Delete Action Method and choose Add View from the list of the menu. After choosing it a new dialog will pop up with name Add View in this dialog just choose template “Delete” and Model class as “CarModel” click on Add button.


Below is a snapshot of Delete View which is generated.


Now let’s save code and run the application.

After running the application just access URL - http://localhost:####/Carinformation/Index

After accessing an Index view will appear as shown in below snapshot.

Then we are going to click on Delete button to see Delete View.


After clicking on Delete button you can see Delete view as shown below.


Now we are able to see Delete View but we cannot delete record because we have not added Delete Action Method which will handle HTTP post request Let’s add it.

In this part, we have written code for handling Http post Delete request which is going to take ObjectId as input parameter and in this parameter we are going to pass to create Mongo Query, and this Mongo Query will be passed to Remove Method which will remove this document from the database.

Snapshot of Delete ActionMethod


Code Snippet 

  1. // POST: Carinformation/Delete/5  
  2.         [HttpPost]  
  3.         public ActionResult Delete(string id, CarModel CarModel)  
  4.         {  
  5.             try  
  6.             {     
  7.                 //Mongo Query  
  8.                 var carObjectid = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));  
  9.                 // Document Collections  
  10.                 var collection = _dbContext._database.GetCollection<CarModel>("CarModel");  
  11.                 // Document Delete which need ObjectId to Delete Data   
  12.                 var result = collection.Remove(carObjectid, RemoveFlags.Single);  
  13.   
  14.                 return RedirectToAction("Index");  
  15.             }  
  16.             catch  
  17.             {  
  18.                 return View();  
  19.             }  
  20.         }   

Now, let’s save the code and run the application.

After running the application, just access this URL: - http://localhost:####/Carinformation/Index

After accessing, an Index View will appear,  as shown in below snapshot. Then, we click on Delete button to see Delete View.


After clicking on "Delete" button, the Delete view will be shown as below. Now, just click on Delete button to delete this record from MongoDB database.


Below is the output after deleting the record


Wow! We have finally come to end of the article. Here we have learned how to perform simple CRUD operation with ASP.NET MVC using MongoDB in step by step way.

Thanks for reading this article. I hope it helped you a lot. Share this article if you liked it.

Finally, before winding up, have a look at this MongoChef tool which is a really cool tool for managing Mongo DB Database. I will explore it in upcoming Mongo DB articles.




Similar Articles