MongoDB CRUD Operations in ASP.Net

Introduction

In this article we will learn how to do the CRUD operations with MongoDB using ASP.NET. MongoDB is a document database and SQL Server is a relational database, often used many times with ASP.NET projects. But this time we will implement  the MongoDB with ASP.NET. The advantage over the SQL-Server is scalability, agility, however these are not the only redeeming qualities that database MongoDB possess.

As we know that MongoDB is a Document Database. This is the new breed of the database, that is designed for storing, retrieving and managing document oriented information. The main objective of this database is to store data in a standard format or encoding. 

Some features of MongoDB are :

  • Continues Data Availability
  • Real Location Independence
  • Flexible Data Models
  • Full Index Support
  • Replication and High Availability
  • Auto-Sharding

Prerequisites

  • Visual Studio
  • MongoDB
  • MongoDB Driver for CSharp

Installation process of MongoDB Driver for C#

The MongoDB Driver was officially developed by the MongoDB Team. We need to download the driver from github or the official website of the MongoDB. There is another way to install driver from Nuget Package Manager from Visual Studio. In this article we will see the installation process through Nuget Package Manager. In this driver are two major classes.

  • BSON Library
  • C# Driver Library   

Step 1

Open the Visual Studio .

Step 2

Choose empty project.

Step 3

Open The Nuget Package Manager.

MongoDBC%23Package

This is the simplest way to install the MongoDB Driver from the Visual Studio. After installation we will get MongoDB.Bson and MongoDB.Driver in the reference folder.

Step 4

Be confirmed after installation.

reference

Step 5

Start the MongoDB Server.

To start the server we need to type "mongod  - - dbpath db" in the command prompt.

bdpath

Step 6

Make a connection in the web config file as in the following:

  1. <connectionStrings>  
  2.   <add name="con" connectionString="Server=127.0.0.1:27017"/>  
  3. </connectionStrings>  

Step 7

Create and select.

  1. public DAL()  
  2. {  
  3.     con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;  
  4.     server = MongoServer.Create(con);  
  5.     emptbl = server.GetDatabase("Employee");  
  6.   
  7. }  
  8. public List<Employee> getEmployeeList()  
  9. {  
  10.      List<Employee> list = new List<Employee>();  
  11.      var collection = emptbl.GetCollection<Employee>("Employee");  

  12.      foreach (Employee emp in collection.FindAll())  
  13.      {  
  14.          list.Add(emp);  
  15.      }  

  16.          return list;  
  17.   
  18. }  

Step 8

Insert.

  1. public void insert(Employee emp)  
  2. {  
  3.     try  
  4.     {  
  5.          MongoCollection<Employee> collection = emptbl.GetCollection<Employee>("Employee");  

  6.          BsonDocument employee = new BsonDocument
  7.          {  
  8.                {"empName",emp.empName},  
  9.                {"empId",emp.empId},  
  10.                {"salary",emp.salary},  
  11.                {"address", emp.address},  
  12.                {"phone",emp.phone}  
  13.          };  

  14.               collection.Insert(employee);  
  15.     }  

  16.         catch { };  
  17. }   

Step 9

Update.

  1. public void updateEmployee(Employee emp)  
  2. {  
  3.      MongoCollection<Employee> collection = emptbl.GetCollection<Employee>("Employee");  
  4.      IMongoQuery query = Query.EQ("_id", emp._id);  
  5.      IMongoUpdate update = MongoDB.Driver.Builders.Update.Set("empName", emp.empName)  
  6.                                                          .Set("empId", emp.empId)  
  7.                                                          .Set("salary", emp.salary)  
  8.                                                          .Set("address", emp.address)  
  9.                                                          .Set("phone", emp.phone);  
  10.      collection.Update(query, update);  
  11.   
  12. }   

Step 10

Delete 

  1. public void DeleteEmployee(ObjectId id)  
  2. {  
  3.      MongoCollection<Employee> collection = emptbl.GetCollection<Employee>("Employee");  
  4.      IMongoQuery query = Query.EQ("_id", id);  
  5.      collection.Remove(query);  
  6. }  
In all these operations, we will now sum up all these things and bind into a GridView in ASP.NET. A GridView have all four operations ( insert, update,select and delete) , so it will be an easy. And before we take the next step we have completed all the important tasks. Install the mongoDB, install the mongoDB driver, create a DAL (Data Access Layer). Now we will use the entire code and implement it into an ASP.NET page. 

HTML Page 
  1.    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CRUD.aspx.cs" Inherits="WebApplication2.CRUD" %>    
  2. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>    
  3. <!DOCTYPE html>    
  4. <html>    
  5. <head id="Head1" runat="server">    
  6.     <title></title>    
  7.     <link href="Script/bootstrap.min.css" rel="stylesheet" />    
  8.     <script src="Script/jquery-1.3.2.min.js"></script>    
  9.     <script src="Script/jquery.blockUI.js"></script>    
  10.     <link href="StyleSheet1.css" rel="stylesheet" />    
  11.     <script type="text/javascript">  
  12.         function BlockUI(elementID) {  
  13.             var prm = Sys.WebForms.PageRequestManager.getInstance();  
  14.             prm.add_beginRequest(function () {  
  15.                 $("#" + elementID).block({  
  16.                     message: '<table align = "center"><tr><td>' +  
  17.              '<img src="loading.gif"/></td></tr></table>',  
  18.                     css: {},  
  19.                     overlayCSS: {  
  20.                         backgroundColor: '#000000', opacity: 0.6  
  21.                     }  
  22.                 });  
  23.             });  
  24.             prm.add_endRequest(function () {  
  25.                 $("#" + elementID).unblock();  
  26.             });  
  27.         }  
  28.         $(document).ready(function () {  
  29.   
  30.             BlockUI("<%=pnlAddEdit.ClientID %>");  
  31.             $.blockUI.defaults.css = {};  
  32.         });  
  33.             function Hidepopup() {  
  34.                 $find("popup").hide();  
  35.                 return false;  
  36.             }  
  37.     </script>    
  38. </head>    
  39. <body>    
  40.     <form id="form1" runat="server">    
  41.         <div>    
  42.     
  43.             <asp:ScriptManager ID="ScriptManager1" runat="server">    
  44.             </asp:ScriptManager>    
  45.             <asp:UpdatePanel ID="UpdatePanel1" runat="server">    
  46.                 <ContentTemplate>    
  47.                     <asp:GridView ID="GridView1" runat="server" Width="700px"    
  48.                         AutoGenerateColumns="false" PageSize="5" HeaderStyle-BackColor="#6699ff" HeaderStyle-ForeColor="WhiteSmoke" AllowPaging="False">    
  49.                         <Columns>    
  50.                             <asp:BoundField DataField="empName" HeaderText="Employee Name" HtmlEncode="true" />    
  51.                             <asp:BoundField DataField="empId" HeaderText="Employee ID" HtmlEncode="true" />    
  52.                             <asp:BoundField DataField="salary" HeaderText="Employee Salary" HtmlEncode="true" />    
  53.                             <asp:BoundField DataField="address" HeaderText="Employee Address" HtmlEncode="true" />    
  54.                              <asp:BoundField DataField="phone" HeaderText="Phone Number" HtmlEncode="true" />    
  55.                             <asp:TemplateField ItemStyle-Width="80px" HeaderText="Edit">    
  56.                                 <ItemTemplate>    
  57.                                      <asp:LinkButton ID="lnkbtn" runat="server"  OnClick="Edit" CommandArgument='<%# Eval("_id") %>'>Edit</asp:LinkButton>      
  58.                                      <asp:LinkButton ID="lnkDel" runat="server"   OnClick="delete" CommandArgument='<%# Eval("_id") %>'>Delete</asp:LinkButton>    
  59.                                 </ItemTemplate>    
  60.                             </asp:TemplateField>    
  61.                         </Columns>    
  62.                     </asp:GridView>    
  63.                      <asp:HiddenField ID="hdn" runat="server" />    
  64.                     <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" CssClass="btn-success" Width="100px" />    
  65.                     <asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" Style="display: none">    
  66.                         <asp:Label Font-Bold="true" ID="Label4" CssClass="lbl" runat="server" Text="Employee Details"></asp:Label>    
  67.                         <br />    
  68.                         <table align="center" class="table">    
  69.                             <tr>    
  70.                                 <td>    
  71.                                     <asp:Label ID="Label1" runat="server" Text="Employee Name"></asp:Label>    
  72.                                 </td>    
  73.                                 <td>    
  74.                                     <asp:TextBox ID="txtEmployeeName" CssClass="control-group info" runat="server"></asp:TextBox>    
  75.                                 </td>    
  76.                             </tr>    
  77.                             <tr>    
  78.                                 <td>    
  79.                                     <asp:Label ID="Label2" runat="server" Text="Employee ID" ></asp:Label>    
  80.                                 </td>    
  81.                                 <td>    
  82.                                     <asp:TextBox ID="txtID" runat="server" CssClass="control-group info"></asp:TextBox>    
  83.                                 </td>    
  84.                             </tr>    
  85.                             <tr>    
  86.                                 <td>    
  87.                                     <asp:Label ID="Label3" runat="server" Text="Employee Salary"></asp:Label>    
  88.                                 </td>    
  89.                                 <td>    
  90.                                     <asp:TextBox ID="txtSal" runat="server" CssClass="control-group info"></asp:TextBox>    
  91.                                 </td>    
  92.                             </tr>    
  93.                             <tr>    
  94.                                 <td>    
  95.                                     <asp:Label ID="Label5" runat="server" Text="Employee Address"></asp:Label>    
  96.                                 </td>    
  97.                                 <td>    
  98.                                     <asp:TextBox ID="txtAddress" runat="server" CssClass="control-group info"></asp:TextBox>    
  99.                                 </td>    
  100.                             </tr>    
  101.                             <tr>    
  102.                                 <td>    
  103.                                     <asp:Label ID="Label6" runat="server" Text="Phone Number"></asp:Label>    
  104.                                 </td>    
  105.                                 <td>    
  106.                                     <asp:TextBox ID="txtPhn" runat="server" CssClass="control-group info"></asp:TextBox>    
  107.                                 </td>    
  108.                             </tr>    
  109.                             <tr>    
  110.                                 <td>    
  111.                                     <asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn-primary"  OnClick="Save" />    
  112.                                 </td>    
  113.                                 <td>    
  114.                                     <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="btn-primary" OnClientClick="return Hidepopup()" />    
  115.                                 </td>    
  116.                             </tr>    
  117.                         </table>    
  118.                     </asp:Panel>    
  119.                     <asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>    
  120.                     <asp:ModalPopupExtender ID="popup" runat="server" DropShadow="false"    
  121.                         PopupControlID="pnlAddEdit" TargetControlID="lnkFake"    
  122.                         BackgroundCssClass="modalBackground">    
  123.                     </asp:ModalPopupExtender>    
  124.                 </ContentTemplate>    
  125.                 <Triggers>    
  126.                     <asp:AsyncPostBackTrigger ControlID="GridView1" />    
  127.                     <asp:AsyncPostBackTrigger ControlID="btnSave" />    
  128.                 </Triggers>    
  129.             </asp:UpdatePanel>    
  130.         </div>    
  131.     </form>    
  132. </body>    
  133. </html>    
Code 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using MongoDB.Driver;  
  8. using MongoDB.Bson;  
  9. using System.Data;  
  10. using System.Configuration;  
  11.   
  12. namespace WebApplication2  
  13. {  
  14.     public partial class CRUD : System.Web.UI.Page  
  15.     {  
  16.         Model.DAL dal = new Model.DAL();  
  17.         protected void Page_Load(object sender, EventArgs e)  
  18.         {  
  19.             if (!IsPostBack)  
  20.             {  
  21.                 LoadEMployee();  
  22.             }  
  23.         }  
  24.   
  25.         private void LoadEMployee()  
  26.         {  
  27.   
  28.             try  
  29.             {  
  30.                 GridView1.DataSource = dal.getEmployeeList().ToList();  
  31.                 GridView1.DataBind();  
  32.             }  
  33.             catch (Exception) { }  
  34.         }  
  35.   
  36.         protected void Save(object sender, EventArgs e)  
  37.         {  
  38.             Employee emp = new Employee();  
  39.             if (hdn.Value == "Edit")  
  40.             {  
  41.                 if (ViewState["_idEdit"] != "")  
  42.                     emp._id = ObjectId.Parse(ViewState["_idEdit"].ToString());  
  43.   
  44.                 emp.empName = txtEmployeeName.Text;  
  45.                 emp.empId = txtID.Text;  
  46.                 emp.salary = Convert.ToDouble(txtSal.Text);  
  47.                 emp.address = txtAddress.Text;  
  48.                 emp.phone = txtPhn.Text;  
  49.                 //dal.insert(emp);  
  50.                 // emp._id = Xid;  
  51.   
  52.                 dal.updateEmployee(emp);  
  53.                 LoadEMployee();  
  54.             }  
  55.             else  
  56.             {  
  57.                 //Employee emp = new Employee();  
  58.                 emp.empName = txtEmployeeName.Text;  
  59.                 emp.empId = txtID.Text;  
  60.                 emp.salary = Convert.ToDouble(txtSal.Text);  
  61.                 emp.address = txtAddress.Text;  
  62.                 emp.phone = txtPhn.Text;  
  63.                 dal.insert(emp);  
  64.                 LoadEMployee();  
  65.             }  
  66.         }  
  67.         protected void Add(object sender, EventArgs e)  
  68.         {  
  69.             txtEmployeeName.Text = string.Empty;  
  70.             txtID.Text = string.Empty;  
  71.             txtSal.Text = string.Empty;  
  72.             txtAddress.Text = string.Empty;  
  73.             txtPhn.Text = string.Empty;  
  74.             popup.Show();  
  75.         }  
  76.         public void Edit(object sender, EventArgs e)  
  77.         {  
  78.             LinkButton btn = (LinkButton)sender;  
  79.             hdn.Value = "Edit";  
  80.             using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)  
  81.             {  
  82.   
  83.                 txtEmployeeName.Text = row.Cells[0].Text;  
  84.                 txtID.Text = row.Cells[1].Text;  
  85.                 txtSal.Text = row.Cells[2].Text;  
  86.                 txtAddress.Text = row.Cells[3].Text;  
  87.                 txtPhn.Text = row.Cells[4].Text;  
  88.                 popup.Show();  
  89.             }  
  90.             ViewState["_idEdit"] = btn.CommandArgument;  
  91.         }  
  92.         protected void delete(object sender, EventArgs e)  
  93.         {  
  94.             LinkButton btn = (LinkButton)sender;  
  95.             Employee emp = new Employee();  
  96.             var x = emp._id;  
  97.             if (btn.Text == "Delete")  
  98.             {  
  99.                 dal.DeleteEmployee(ObjectId.Parse(btn.CommandArgument));  
  100.                 LoadEMployee();  
  101.             }  
  102.             else  
  103.             {  
  104.                 hdn.Value = "Edit";  
  105.             }  
  106.         }  
  107.   
  108.     }  
  109. }  
Output: Displayed all records in GridView.

output1

Output:  When we hit the Add button, this pop up box will display for inserting a new record.

output2 

Output: When we hit the edit button , we can edit any record.

output3

Summary

In this article we learned the Mongo C# driver and how the driver interacts with the MongoDB server. We also learned the basic CRUD operations using the Mongo Driver.