Getting Started With MongoDB and MVC

 

Introduction

This article shows how to use a mongoDB to communicate with ASP.NET. We will create a simple MVC application that retrieves pictures from a mongoDB.

You can see my other articles of mongoDB from here.

Previous articles have provided an introduction to mongoDB, the installation of it and communicating with ASP.NET. You can get them from the following:

Let us start creating the project from scratch using the following step-by-step procedure.

  • Step 1 Create a new project; open Visual Studio 2013 then click "File" -> "New" -> "Project..." then create an "ASP.NET Web Application".

In the Templates pane, select "Installed Templates" and expand the Visual C# node. Under Visual C#, select "Web". In the list of project templates, select "ASP.NET MVC Web Application". Name the project "MongoAndMVC".

 
 

In the New ASP.NET Project dialog, select the MVC template.

 
 
 This creates an outline project that is configured for MVC functionality.
  • Step 2 Now add mongocsharpdriver using the Library Package Manager as in the following:

 
 
 
 
  • Step 3 Next, add classes for domain models. In Solution Explorer, right-click the Models folder. Select "Add", then select "Class". Name the class "MongoPictureModel".

 
 
 

Add the following properties to the model class:

  1. using MongoDB.Bson;  
  2.   
  3. namespace MongoAndMVC.Models  
  4. {  
  5.     public class MongoPictureModel  
  6.     {  
  7.         public class MongoPictureModel  
  8.         {  
  9.             public ObjectId _Id { getset; }  
  10.   
  11.             public string FileName { getset; }  
  12.   
  13.             public string PictureDataAsString { getset; }  
  14.         }  
  15.     }  
  16. }  
 
  •  Step 4  Now add the controller as in the following:

 
 

 

  1. using MongoDB.Bson;  
  2. using MongoDB.Driver;  
  3. using MongoDB.Driver.Builders;  
  4. using MongowithMVC.Models;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.IO;  
  8. using System.Linq;  
  9. using System.Web;  
  10. using System.Web.Mvc;  
  11.   
  12. namespace MongowithMVC.Controllers  
  13. {  
  14.     public class ImageGalleryController : Controller  
  15.     {  
  16.         //  
  17.         // GET: /ImageGallery/  
  18.         public ActionResult Index()  
  19.         {  
  20.             var theModel = GetTheImages();  
  21.             return View(theModel);  
  22.         }  
  23.   
  24.         public ActionResult AddImage()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public ActionResult AddPicture(HttpPostedFileBase theFile)  
  31.         {  
  32.             if (theFile.ContentLength > 0)  
  33.             {  
  34.                 //get the file's name  
  35.                 string theFileName = Path.GetFileName(theFile.FileName);  
  36.   
  37.                 //get the bytes from the content stream of the file  
  38.                 byte[] thePictureAsBytes = new byte[theFile.ContentLength];  
  39.                 using (BinaryReader theReader = new BinaryReader(theFile.InputStream))  
  40.                 {  
  41.                     thePictureAsBytes = theReader.ReadBytes(theFile.ContentLength);  
  42.                 }  
  43.   
  44.                 //convert the bytes of image data to a string using the Base64 encoding  
  45.                 string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);  
  46.   
  47.                 //create a new mongo picture model object to insert into the db  
  48.                 MongoPictureModel thePicture = new MongoPictureModel()  
  49.                 {  
  50.                     FileName = theFileName,  
  51.                     PictureDataAsString = thePictureDataAsString  
  52.                 };  
  53.   
  54.                 //insert the picture object  
  55.                 bool didItInsert = InsertPictureIntoDatabase(thePicture);  
  56.   
  57.                 if (didItInsert)  
  58.                     ViewBag.Message = "The image was updated successfully";  
  59.                 else  
  60.                     ViewBag.Message = "A database error has occured";  
  61.             }  
  62.             else  
  63.                 ViewBag.Message = "You must upload an image";  
  64.   
  65.             return View();  
  66.         }  
  67.   
  68.         /// <summary>  
  69.         /// This method will insert the image into the db  
  70.         /// </summary>  
  71.         /// <param name="thePicture"></param>  
  72.         /// <returns></returns>  
  73.         private bool InsertPictureIntoDatabase(MongoPictureModel thePicture)  
  74.         {  
  75.             var thePictureColleciton = GetImageCollection();  
  76.             var theResult = thePictureColleciton.Insert(thePicture);  
  77.             return theResult.Ok;  
  78.         }  
  79.   
  80.         /// <summary>  
  81.         /// This method will return just the id's and filenames of the images to use to retrieve the image from the db  
  82.         /// </summary>  
  83.         /// <returns></returns>  
  84.         private List<MongoPictureModel> GetTheImages()  
  85.         {  
  86.             var thePictureColleciton = GetImageCollection();  
  87.             var thePictureCursor = thePictureColleciton.FindAll();  
  88.   
  89.             //use SetFields to just return the id and the name of the picture instead of the entire document  
  90.             thePictureCursor.SetFields(Fields.Include("_id""FileName"));  
  91.   
  92.             return thePictureCursor.ToList() ?? new List<MongoPictureModel>();  
  93.         }  
  94.   
  95.         /// <summary>  
  96.         /// This action will return an image result to render the data from the picture as a jpeg  
  97.         /// </summary>  
  98.         
  99.         /// <returns></returns>  
  100.         public FileContentResult ShowImage(string id)  
  101.         {  
  102.             var thePictureColleciton = GetImageCollection();  
  103.   
  104.             //get pictrue document from db  
  105.             var thePicture = thePictureColleciton.FindOneById(new ObjectId(id));  
  106.   
  107.             //transform the picture's data from string to an array of bytes  
  108.             var thePictureDataAsBytes = Convert.FromBase64String(thePicture.PictureDataAsString);  
  109.   
  110.             //return array of bytes as the image's data to action's response. We set the image's content mime type to image/jpeg  
  111.             return new FileContentResult(thePictureDataAsBytes, "image/jpeg");  
  112.         }  
  113.   
  114.         /// <summary>  
  115.         /// This will return the mongoDB image collection object to use do data related actions  
  116.         /// </summary>  
  117.         /// <returns></returns>localhost:27017  
  118.         private MongoCollection<MongoPictureModel> GetImageCollection()  
  119.         {  
  120.             //set this to what ever your connection is or from config  
  121.             var theConnectionString = "mongodb://localhost";  
  122.   
  123.             //get the mongo db client object  
  124.             var theDBClient = new MongoClient(theConnectionString);  
  125.   
  126.             //get reference to db server  
  127.             var theServer = theDBClient.GetServer();  
  128.   
  129.             //gets the database , if it doesn't exist it will create a new one  
  130.             string databaseName = "PictureApplication";//replace with whatever name you choose  
  131.             var thePictureDB = theServer.GetDatabase(databaseName);  
  132.   
  133.             //finally attempts to get a collection, if not there it will make a new one  
  134.             string theCollectionName = "pictures";  
  135.             var thePictureColleciton = thePictureDB.GetCollection<MongoPictureModel>(theCollectionName);  
  136.   
  137.             return thePictureColleciton;  
  138.         }  
  139.     }  
  140. }  

 

We have added some new namespaces from the Mongo driver library to help us access the mongoDB and to provide us access to some very useful classes for manipulating the mongoDB data.

MongoAndMVC.Models;
MongoDB.Bson;
MongoDB.Driver;
MongoDB.Driver.Builders;

We also added the "System.IO" namespace for some of the byte manipulation that we'll be doing.

Now add  the index view and add an image view in the imagegallery folder with the following implementation:

  1. @model List<MongoAndMVC.Models.MongoPictureModel>  
  2. @{  
  3.     ViewBag.Title = "Gallery";  
  4. }  
  5.   
  6. <h2>Image Gallery</h2>  
  7.   
  8. @Html.ActionLink("Add a new Picture", "AddPicture")  
  9.   
  10. @foreach (var image in Model)  
  11. {  
  12.     <div>  
  13.         @image.FileName<br />  
  14.         <img src="@string.Format("/Gallery/ShowPicture/{0}", image._id.ToString())" alt="@image.FileName" />  
  15.     </div>  
  16. }  
 
  1. @{  
  2.     ViewBag.Title = "Upload an image";  
  3. }  
  4.   
  5. <h2>Upload a new image</h2>  
  6. @Html.ActionLink("View Gallery", "Index")  
  7.   
  8. <div>  
  9.     @if (ViewBag.Message != null && ViewBag.Message != "")  
  10.     {  
  11.         @ViewBag.Message  
  12.     }  
  13. </div>  
  14.   
  15. <form action="" method="post" enctype="multipart/form-data">  
  16.     <input type="file" id="theFile" name="theFile" />  
  17.     <br />  
  18.     <button type="submit">Upload Image</button>  
  19. </form>  
 
 Also edit the layout.cshtml file in the shared folder under views and add a link to the index action of the gallery controller in the app's navigation.
 
 
Let's check the output by uploading our vulpes image.
 
 
 
 
Summary
In this article we saw how to use MongoDB with an ASP.NET MVC application. I hope you have understood.

Up Next
    Ebook Download
    View all
    Learn
    View all