Displaying records from MongoDB in an ASP.NET MVC Application

In a previous post I explained how to save a Twitter stream to a MongoDB using C#. In this post I will show you how to build an ASP.NET MVC application to display those records.

The example that follows was built using Visual Studio 2015 Community Edition and MongoDB 3.4.6.

Firstly this is how the data looks in Mongo. I start a new start Mongo shell, select the database of interest, in this case twitterstream and then using db.auth I authenticate myself as the demouser

and execute a find which displays the data in a hard to read JSON format.  (redacted)

The next step is switch to Visual Studio and create a new ASP.NET Web Application (.NET Framework)

Select Ok.

Accept the defaults and again select Ok.

Now add the following packages via NuGet

  • mongocsharpdriver (Version used 2.4.4)
  • MongoDB.Driver (Version used 2.4.4)

Open the Web.config files and add the following MongoDB entries within the appSettings element.

<add key="MongoDatabaseName" value="twitterstream" />;
<add key="MongoUsername" value="demouser" />;
<add key="MongoPassword" value="abcd" />;
<add key="MongoPort" value="27017" />;
<add key="MongoHost" value="localhost" />;

These values identify your MongoDB so if you are using a different database, user etc. modify these values as appropriate. Here are these same values within Web.config

 

 

 

 

 

 

 

 

 

Within the App_Start folder create a new class called MongoContext and add the following code:

using System;
using MongoDB.Driver;

namespace DisplayMongoData99.App_Start
{
  public class MongoContext
  {
    MongoClient _client;
    MongoServer _server;

    public MongoDatabase _database;

    public MongoContext()
    {
      // reading creditials from web.config file
     var MongoDatabaseName = System.Configuration.ConfigurationManager.AppSettings["MongoDatabaseName"];
     var MongoUsername = System.Configuration.ConfigurationManager.AppSettings["MongoUsername"];
     var MongoPassword = System.Configuration.ConfigurationManager.AppSettings["MongoPassword"];
     var MongoPort = System.Configuration.ConfigurationManager.AppSettings["MongoPort"];
     var MongoHost = System.Configuration.ConfigurationManager.AppSettings["MongoHost"];

     // creating creditials
     var credential = MongoCredential.CreateMongoCRCredential(MongoDatabaseName, MongoUsername, MongoPassword);

     // creating MongoClientSettings
     var settings = new MongoClientSettings
     {
       Credentials = new[] { credential },
       Server = new MongoServerAddress(MongoHost, Convert.ToInt32(MongoPort))
     };

     _client = new MongoClient(settings);
     _server = _client.GetServer();
     _database = _server.GetDatabase(MongoDatabaseName);
   }
  }
}

This class setups a connection to the MongoDB instance.  It reads the values from the parameters within Web.config and then calls the MongoClientSettings constructor, setting the  Credentials and Server properties.

Within the Models folder create a new class called TweetModel.cs and add the following code

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace DisplayingMongoDB4.Models
{
  public class TweetModel
  {
    [BsonId]
    public ObjectId Id { get; set; }

    [BsonElement("thetweet")]
    public string Tweet { get; set; }
  }
}

The TweetModel class represents the data that will be returned by MongoDB. In this case the object id and the tweet.

The next step is to create a new controller. So right click on the Controllers Folder and select Add then Controller. You should then see the following dialog window:

Choose “MVC 5 Controller with read/write actions”, select Add and give it a meaningful name; in this example I have used TweetController. Click add again and Visual Studio will then create the TweetController.cs.

Now amend TweetController.cs as shown below:

using System.Linq;
using System.Web.Mvc;
using DisplayMongoData99.App_Start;
using DisplayMongoData99.Models;

namespace DisplayMongoData99.Controllers
{
  public class TweetController : Controller
  {
    MongoContext _dbContext;

    public TweetController()
    {
      _dbContext = new MongoContext();
    }

    // GET: Tweet
    public ActionResult Index()
    {
      var tweetDetails = _dbContext._database.GetCollection<TweetModel>("tweets").FindAll().ToList();
      return View(tweetDetails);
    }
...
rest of existing scaffolding code here which remains unchanged... 
public ActionResult Details(int id)
...

The changes introduce a new constructor which creates a new MongoContext object. The changes to the Index() method queries the MongoDB database for a collection called “tweets” which will be returned to the View. All the rest of the scaffolding code created by Visual Studio is unchanged.

The final step is right click inside the Index() method and select AddView. This will bring up another dialog window which you should complete as follows:

 

Pressing add results in Visual Studio creating more scaffolding code which when complete should display the following:

 Pressing the “Microsoft Edge” (Or whichever browser you have previously selected) button will launch the Application and after a few moments you will see your MongoDB data displayed.

 

Summary

In this post I have demonstrated how to get started in displaying the content of a MongoDB database from an ASP.net MVC application.

I have skipped over the challenges I encountered in getting the security of my MongoDB set up correctly and that the out of the box display of the data is dreadful at best so if you would like to see further posts on the security or getting the display more production like sound off in the comments.

Acknowledgements

This post would not have been possible without the generosity of these following two posts:

  1. http://www.c-sharpcorner.com/article/simple-crud-operation-using-asp-net-mvc-and-mongodb/
  2. https://www.claudiokuenzler.com/blog/553/authentication-mongodb-3.x-failed-with-mechanism-mongodb-cr