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

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. <h2>Image Gallery</h2>
  6. @Html.ActionLink("Add a new Picture", "AddPicture")
  7. @foreach (var image in Model)
  8. {
  9. <div>
  10. @image.FileName<br />
  11. <img src="@string.Format("/Gallery/ShowPicture/{0}", image._id.ToString())" alt="@image.FileName" />
  12. </div>
  13. }
  1. @{
  2. ViewBag.Title = "Upload an image";
  3. }
  4. <h2>Upload a new image</h2>
  5. @Html.ActionLink("View Gallery", "Index")
  6. <div>
  7. @if (ViewBag.Message != null && ViewBag.Message != "")
  8. {
  9. @ViewBag.Message
  10. }
  11. </div>
  12. <form action="" method="post" enctype="multipart/form-data">
  13. <input type="file" id="theFile" name="theFile" />
  14. <br />
  15. <button type="submit">Upload Image</button>
  16. </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.